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

JavaScript失焦时标签页标题循环切换实现方法咨询

标签页失焦标题轮播实现方案

你不需要写复杂循环逻辑,借助setInterval定时器就能实现间隔切换效果,核心是要在标签页重新聚焦时及时清除定时器,避免逻辑持续运行。

实现要点

  • 单独用变量存储定时器ID,聚焦时可以精准清除轮询任务,避免内存泄漏
  • 把所有失焦提示语存入数组,用索引值标记当前显示的提示项,通过取模运算实现索引循环
  • 失焦触发时先重置显示状态,避免上一次轮播的位置影响本次显示效果
  • 开启新定时器前先清除已存在的旧定时器,防止失焦事件多次触发时出现多定时器并行、切换速度异常的问题

完整修改后代码

<script>
    // 失焦状态下轮播的提示语,后续要加新提示直接往数组里追加即可
    const blurTipList = ["Come Back", "Don't Forget"];
    const originalPageTitle = document.title;
    let switchTimer = null;
    let currentTipIndex = 0;

    window.onblur = function() {
        // 失焦瞬间先显示第一条提示,重置轮播位置
        currentTipIndex = 0;
        document.title = blurTipList[currentTipIndex];
        // 清理残留的旧定时器
        if (switchTimer) clearInterval(switchTimer);
        // 启动1秒间隔的切换任务
        switchTimer = setInterval(() => {
            currentTipIndex = (currentTipIndex + 1) % blurTipList.length;
            document.title = blurTipList[currentTipIndex];
        }, 1000);
    }

    window.onfocus = function() {
        // 清除轮播任务
        if (switchTimer) {
            clearInterval(switchTimer);
            switchTimer = null;
        }
        // 还原页面原始标题
        document.title = originalPageTitle;
    }
</script>

补充说明

代码里用(currentTipIndex + 1) % blurTipList.length计算索引,会自动在0到数组长度-1之间循环,不需要手动写判断跳转逻辑,扩展性更强,如果后续要加第三条、第四条失焦提示,直接往blurTipList数组里加对应字符串即可,不需要修改其他逻辑。

内容的提问来源于stack exchange,提问作者Ben Titmas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 14:15:42