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

如何让HTML与JS记住用户深色主题设置,刷新页面不恢复默认

主题持久化修复方案

你当前的代码仅在点击切换按钮时设置了一次暗色主题Cookie,缺失两个核心逻辑:

  • 页面加载时没有读取已保存的主题偏好并自动应用
  • 切换回亮色主题时没有更新存储的偏好值

推荐优先用更易用的localStorage实现,完整修改后的JS代码如下:

var icon = document.getElementById("icon");

// 页面加载时自动应用已保存的主题
window.addEventListener('load', () => {
  const savedTheme = localStorage.getItem('beast-bot-theme');
  if (savedTheme === 'dark') {
    document.body.classList.add('dark-theme');
    icon.src = "images/sun.png";
  } else {
    document.body.classList.remove('dark-theme');
    icon.src = "images/moon.png";
  }
})

// 切换主题逻辑
icon.onclick = function(){
  document.body.classList.toggle("dark-theme");
  if(document.body.classList.contains("dark-theme")){
    localStorage.setItem('beast-bot-theme', 'dark');
    icon.src = "images/sun.png";
  }else{
    localStorage.setItem('beast-bot-theme', 'light');
    icon.src = "images/moon.png"
  }
}

如果你需要使用Cookie实现,只需替换存储逻辑即可,注意给Cookie添加有效期和全站路径配置,避免跨页面失效:

  • 写Cookie示例:document.cookie = "theme=dark; max-age=31536000; path=/";(max-age单位为秒,31536000对应1年有效期)
  • 读Cookie需要自行编写解析逻辑,操作复杂度高于localStorage,无特殊需求优先使用上述localStorage方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 20:36:06