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

如何在现有主题切换JS代码中使用localStorage存储用户所选主题

localStorage主题持久化改造方法

只需要在你原有代码基础上补充两处逻辑,就能实现刷新页面后用户选择的主题不丢失:

  • 页面首次加载时,从localStorage读取之前保存的主题值,同步应用到页面根节点,同时把对应的主题单选按钮设为选中状态
  • 用户触发主题切换操作时,除了原有的主题切换逻辑,额外把当前选中的主题值写入localStorage存储

改造后的完整代码如下:

const htmlEl = document.documentElement;
const radios = document.getElementsByName('theme');
// 自定义localStorage存储的key名,可自行修改
const THEME_STORAGE_KEY = 'user-selected-theme';

// 初始化:读取本地存储的主题配置
const savedTheme = localStorage.getItem(THEME_STORAGE_KEY);
if (savedTheme) {
  // 应用已保存的主题
  htmlEl.setAttribute('data-theme', savedTheme);
  // 同步单选框选中状态
  Array.from(radios).forEach(radio => {
    radio.checked = radio.getAttribute('value') === savedTheme;
  });
}

// 原有主题切换逻辑,新增存储写入操作
Array.from(radios).forEach((el) => {
  el.addEventListener('change', e => {
    if (e.target.checked) {
      const currentTheme = e.target.getAttribute('value');
      htmlEl.setAttribute('data-theme', currentTheme);
      // 将当前选中主题写入本地存储
      localStorage.setItem(THEME_STORAGE_KEY, currentTheme);

      htmlEl.classList.add('in-transition');
      window.setTimeout(function() {
        htmlEl.classList.remove('color-theme-in-transition');
      }, 1000);
    }
  });
});

小提示:如果你需要配置默认主题,只需要在读取存储的判断分支中增加else逻辑,给根节点设置默认的data-theme值、选中对应默认主题的单选框即可。localStorage直接存取字符串即可,不需要做JSON序列化/反序列化操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 20:18:29