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

Local Storage无法永久保存夜间模式设置 代码问题排查求助

问题原因

你的代码存在2处核心逻辑错误:

  • 类名不统一:页面初始化读取localStorage后,给根元素添加的是night-mode类,但点击切换时操作的是dark类,二者不一致导致初始化时就算读取到夜间模式开启状态,也不会生效
  • localStorage操作逻辑错误:
    1. 关闭夜间模式时调用localStorage.setItem('gmtNightMode')缺少第二个必填参数,实际会写入无效值,无法正确存储关闭状态
    2. 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下你的站点域名:

  1. 点击切换按钮时,观察gmtNightMode字段是否正常新增/移除
  2. 刷新页面后,确认gmtNightMode字段还存在,同时html根元素已带上dark类

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 01:36:03