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

如何使用JavaScript实现切换页面时保持Light Mode状态?

页面切换时亮色模式无法保持的解决方案

问题背景

网站默认采用深色模式,已添加亮色模式切换按钮,但切换页面后亮色模式无法维持,当前使用两段重复的切换函数分别处理首页和信息页的模式切换,尝试if语句未解决问题。

解决方案

核心思路是用localStorage存储用户的模式选择,页面加载时读取该状态并自动应用,同时统一切换逻辑避免重复代码:

1. 统一模式切换函数

替换原有两个重复函数,用一个通用函数处理所有页面的模式切换:

function toggleLightMode() {
    // 切换body的亮色模式类
    const body = document.body;
    const isLightMode = body.classList.toggle("light-mode");

    // 切换按钮文字
    const button = document.getElementById('lightModeButton');
    button.textContent = isLightMode ? "Dark" : "Light";

    // 切换footer样式
    const footer = document.getElementById('footer');
    footer.classList.toggle("footer-color");
    // 注意:classList不能直接操作后代选择器,footer内的a标签样式建议通过CSS继承实现,比如.footer-color a { ... }
    // 若必须用JS操作,可选择footer内的所有a标签:
    // const footerLinks = footer.querySelectorAll('a');
    // footerLinks.forEach(link => link.classList.toggle('footer-link-light'));

    // 处理信息页的文字样式(仅在存在这些元素时执行)
    const textElements = document.querySelectorAll('#textInformation, #textInformation2, #h1Information');
    textElements.forEach(el => el.classList.toggle("text-when-light"));

    // 将当前模式状态存入localStorage
    localStorage.setItem('lightModeEnabled', isLightMode);
}

2. 页面加载时自动恢复模式

在所有页面的脚本中添加初始化代码,读取localStorage并应用模式:

document.addEventListener('DOMContentLoaded', () => {
    // 从localStorage读取模式状态,默认false(深色模式)
    const isLightMode = localStorage.getItem('lightModeEnabled') === 'true';
    
    if (isLightMode) {
        // 应用亮色模式
        document.body.classList.add("light-mode");
        document.getElementById('lightModeButton').textContent = "Dark";
        document.getElementById('footer').classList.add("footer-color");
        
        // 处理信息页文字
        const textElements = document.querySelectorAll('#textInformation, #textInformation2, #h1Information');
        textElements.forEach(el => el.classList.add("text-when-light"));
    } else {
        // 保持深色模式,设置按钮文字为Light
        document.getElementById('lightModeButton').textContent = "Light";
    }

    // 给切换按钮绑定统一的点击事件
    document.getElementById('lightModeButton').addEventListener('click', toggleLightMode);
});

3. 优化CSS样式(可选)

避免用JS操作后代选择器,通过CSS继承简化样式控制:

/* 深色模式下的footer链接样式 */
footer a {
    color: #ccc;
}
/* 亮色模式下的footer链接样式 */
.footer-color a {
    color: #333;
}

关键说明

  • localStorage会持久保存用户选择,除非用户清除浏览器缓存
  • 统一函数后无需为不同页面写重复代码,降低维护成本
  • 初始化时通过DOMContentLoaded确保DOM加载完成后再执行操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 17:40:23