Local Storage无法永久保存夜间模式设置 代码问题排查求助
问题原因
你的代码存在2处核心逻辑错误:
- 类名不统一:页面初始化读取localStorage后,给根元素添加的是
night-mode类,但点击切换时操作的是dark类,二者不一致导致初始化时就算读取到夜间模式开启状态,也不会生效 - localStorage操作逻辑错误:
- 关闭夜间模式时调用
localStorage.setItem('gmtNightMode')缺少第二个必填参数,实际会写入无效值,无法正确存储关闭状态 - localStorage仅支持存储字符串类型,直接存入布尔值
true会被自动转为字符串"true",属于不规范写法,后续可能引发判断逻辑异常
- 关闭夜间模式时调用
修正后代码
<script> (function (window, document, undefined) { 'use strict'; if (!('localStorage' in window)) return; var nightMode = localStorage.getItem('gmtNightMode'); // 统一使用dark类名,和切换逻辑保持一致,同时显式判断值避免误判 if (nightMode === 'true') { document.documentElement.classList.add('dark'); } })(window, document); (function (window, document, undefined) { 'use strict'; if (!('localStorage' in window)) return; var nightMode = document.querySelector("#night-mode"); // 新增元素判空,避免切换按钮不存在时控制台报错 if (!nightMode) return; nightMode.addEventListener('click', function (event) { event.preventDefault(); document.documentElement.classList.toggle('dark'); if (document.documentElement.classList.contains('dark')) { // 显式存入字符串,避免类型转换异常 localStorage.setItem('gmtNightMode', 'true'); return; } // 关闭时直接移除存储项,逻辑更清晰 localStorage.removeItem('gmtNightMode'); }, true); })(window, document); </script>
验证方法
打开Chrome调试工具的「Application」面板,在左侧存储栏找到LocalStorage下你的站点域名:
- 点击切换按钮时,观察
gmtNightMode字段是否正常新增/移除 - 刷新页面后,确认
gmtNightMode字段还存在,同时html根元素已带上dark类
内容的提问来源于stack exchange,提问作者Godda
相关产品推荐
相关产品推荐

