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

如何实现跨页面实时文本显示切换器,状态持久化且每日自动重置

实现方案(纯前端零后端,代码量极小)

核心基于浏览器同域名localStorage共享特性+storage事件实现,无需额外服务端依赖,总代码不足50行,完全满足所有需求。


实现逻辑

  • 状态存在本地localStorage中,同域名下两个页面可共享读取
  • 存储时附带日期标记,每次读取状态先判断是否为当日数据,非当日自动重置为OFF,满足午夜自动重置需求
  • 监听浏览器原生storage事件,开关状态变更时另一个页面可实时收到通知更新,无需轮询

完整代码

toggler.html(开关页)

<!DOCTYPE html>
<html>
<body>
  <label>文本显示开关:<input type="checkbox" id="toggle"></label>
  <script>
    const toggle = document.getElementById('toggle')
    const today = new Date().toDateString()
    // 初始化状态,跨天自动重置
    if (localStorage.getItem('updateDate') !== today) {
      localStorage.setItem('switchState', 'off')
      localStorage.setItem('updateDate', today)
    }
    toggle.checked = localStorage.getItem('switchState') === 'on'
    // 开关变更同步到存储
    toggle.addEventListener('change', e => {
      localStorage.setItem('switchState', e.target.checked ? 'on' : 'off')
      localStorage.setItem('updateDate', today)
    })
  </script>
</body>
</html>

index.html(展示页)

<!DOCTYPE html>
<html>
<body>
  <div id="targetText" style="display:none">要控制显示的指定TEXT</div>
  <script>
    const text = document.getElementById('targetText')
    // 更新文本显示状态
    function refreshState() {
      const today = new Date().toDateString()
      if (localStorage.getItem('updateDate') !== today) {
        localStorage.setItem('switchState', 'off')
        localStorage.setItem('updateDate', today)
      }
      text.style.display = localStorage.getItem('switchState') === 'on' ? 'block' : 'none'
    }
    refreshState()
    // 监听开关页的状态变更,实时更新
    window.addEventListener('storage', refreshState)
  </script>
</body>
</html>

需求匹配说明

  • 实时生效:开关状态变更后,storage事件会在展示页立即触发更新,延迟低于10ms
  • 刷新保持:状态持久化存在本地存储中,刷新页面后读取存储值即可保持原有显示状态
  • 午夜重置:每次读取状态都会校验日期,只要进入新的自然日,状态会自动重置为默认OFF,无需后台定时器,无时间误差

内容的提问来源于stack exchange,提问作者C4DXYZ-SO

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 01:06:05