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

如何防止页面切换时明暗模式切换函数重置状态?

解决暗色模式切换后页面跳转丢失设置的问题

你的问题出在没有持久化保存用户的模式选择,当前代码只是在页面运行时临时修改样式,页面跳转或刷新后,浏览器重新加载脚本,自然回到默认的亮色模式。

要解决这个问题,我们可以用localStorage存储用户的模式偏好,页面加载时读取存储值并应用对应的样式,点击切换按钮时同步更新存储内容。

修改后的代码如下:

const toggle = document.getElementById('toggleDark');
const body = document.querySelector('body');
const element = document.getElementById("id01");
const a = document.querySelector('a');

// 统一处理主题样式与图标切换
function applyTheme(theme) {
  if (theme === 'dark') {
    body.style.background = '#151515';
    body.style.color = 'white';
    body.style.transition = '0.5s';
    element.innerHTML = "lights on";
    a.style.color = 'white';
    toggle.classList.add('bi-moon');
    toggle.classList.remove('bi-brightness-high-fill');
  } else {
    body.style.background = 'white';
    body.style.color = '#151515';
    body.style.transition = '0.5s';
    element.innerHTML = "lights off";
    a.style.color = '#151515';
    toggle.classList.add('bi-brightness-high-fill');
    toggle.classList.remove('bi-moon');
  }
}

// 页面初始化:读取本地存储的主题,无存储则默认亮色
const savedTheme = localStorage.getItem('theme') || 'light';
applyTheme(savedTheme);

toggle.addEventListener('click', function(){
  const currentTheme = localStorage.getItem('theme') || 'light';
  const newTheme = currentTheme === 'light' ? 'dark' : 'light';
  
  // 更新本地存储的主题偏好
  localStorage.setItem('theme', newTheme);
  // 应用新主题
  applyTheme(newTheme);
});

关键改动说明:

  • 新增applyTheme函数,把亮色/暗色模式的样式、图标切换逻辑统一封装,避免重复代码
  • 页面加载时自动读取localStorage里的theme值,没有存储记录则默认使用亮色模式,直接应用对应样式
  • 点击切换按钮时,根据当前主题切换为相反模式,同时更新本地存储的主题值

这样用户切换模式后,选择会被保存在浏览器本地,跳转其他页面时脚本会自动读取存储值并应用对应模式,不会再重置为默认亮色。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 20:48:22