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

基于JS和CSS的主题切换器:如何持久化用户主题选择

主题切换器持久化用户选择解决方案

你需要在两个关键环节处理localStorage:页面加载时恢复用户之前的选择,以及切换主题时保存当前选择。以下是修改后的完整代码,完美适配你的5种主题radio按钮:

var radios = document.getElementsByName('theme');
const currentTheme = localStorage.getItem('theme');

// 页面加载时恢复主题和选中状态
if (currentTheme) {
  // 设置html的data-theme属性
  document.documentElement.setAttribute('data-theme', currentTheme);
  // 找到对应主题的radio并设为选中
  Array.from(radios).forEach(radio => {
    if (radio.getAttribute('value') === currentTheme) {
      radio.checked = true;
    }
  });
}

// 绑定radio切换事件
Array.from(radios).forEach(el => {
  el.addEventListener('change', e => {
    if (e.target.checked) {
      const selectedTheme = e.target.getAttribute('value');
      // 设置主题
      document.documentElement.setAttribute('data-theme', selectedTheme);
      // 保存到localStorage
      localStorage.setItem('theme', selectedTheme);
      // 处理过渡动画(修正原代码类名不一致问题)
      document.documentElement.classList.add('in-transition');
      window.setTimeout(() => {
        document.documentElement.classList.remove('in-transition');
      }, 1000);
    }
  });
});

关键修改点说明:

  • 初始化恢复:页面加载时读取localStorage中的theme值,同步设置html的data-theme,同时找到对应value的radio按钮标记为选中,解决刷新后主题重置、选中状态消失的问题。
  • 保存选择:每次切换主题时,通过localStorage.setItem('theme', selectedTheme)将当前选中的主题值存入本地存储,确保下次访问时能读取到。
  • 修正过渡类名:原代码中添加的是in-transition,但移除的是color-theme-in-transition,这里统一为in-transition,避免过渡动画无法正常结束。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 11:55:27