You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

页面刷新后如何保持停留在最后使用的tab标签页上

实现方案

核心思路是使用浏览器本地存储localStorage持久化记录最后一次激活的tab索引,页面加载时优先读取存储的索引作为默认展示tab,修改后的完整代码如下:

<script>
    const tabBtn = document.querySelectorAll(".tab");
    const tab = document.querySelectorAll(".tabShow");
    function tabs(panelIndex){
        tab.forEach(function(node){
            node.style.display="none";
        });
        tab[panelIndex].style.display="block";
        // 同步切换tab按钮的激活状态
        tabBtn.forEach(function(btn, idx){
            idx === panelIndex ? btn.classList.add("active") : btn.classList.remove("active")
        })
        // 存储当前激活的tab索引到本地
        localStorage.setItem("lastActiveTab", panelIndex)
    }
    // 初始化时优先读取本地存储的索引,无存储记录则用默认值0
    const defaultTab = localStorage.getItem("lastActiveTab") ? Number(localStorage.getItem("lastActiveTab")) : 0
    tabs(defaultTab);
    $(".tab").click(function(){
        // 获取当前点击的tab索引并触发切换
        const currentIndex = $(this).index()
        tabs(currentIndex)
    });
</script>
可选调整项
  • 如果需要关闭浏览器后就清除记忆的tab状态,把代码里的localStorage替换为sessionStorage即可
  • 如果tab存在动态增删的场景,可以给每个tab设置唯一id,存储id值代替索引,避免索引混乱导致的展示错误

内容的提问来源于stack exchange,提问作者marc-stupid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 09:24:01