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

HTML/CSS/JS场景下切换页面或刷新时如何保存已选中的主题?

主题切换状态持久化实现方案

核心实现逻辑是通过浏览器本地存储localStorage持久化保存用户选择的主题标识,页面每次加载时优先读取本地存储的配置,自动加载对应样式表即可实现刷新、跨页面的主题状态保持。

实现步骤

  • 给主题切换交互绑定点击事件,切换样式表的同时将当前选中的主题标识写入localStorage
  • 页面初始化时优先读取localStorage中存储的主题配置,匹配加载对应样式表,无存储值时加载默认样式

完整代码示例

HTML 结构

<!-- 样式表链接,默认加载浅色主题样式,绑定id方便修改href属性 -->
<link rel="stylesheet" id="theme-style" href="light.css">

<!-- 主题切换按钮 -->
<button id="toggle-btn">切换深色主题</button>

JS 逻辑

// 页面DOM加载完成后执行初始化逻辑
document.addEventListener('DOMContentLoaded', () => {
  const styleEl = document.getElementById('theme-style');
  const toggleBtn = document.getElementById('toggle-btn');
  // 读取本地存储的主题配置,默认值为light(浅色模式)
  const savedTheme = localStorage.getItem('user-theme') || 'light';

  // 初始化加载对应主题
  if (savedTheme === 'dark') {
    styleEl.href = 'dark.css';
    toggleBtn.textContent = '切换浅色主题';
  } else {
    styleEl.href = 'light.css';
    toggleBtn.textContent = '切换深色主题';
  }

  // 绑定点击切换事件
  toggleBtn.addEventListener('click', () => {
    const currentTheme = styleEl.href.includes('light.css') ? 'light' : 'dark';
    if (currentTheme === 'light') {
      // 切换为深色主题
      styleEl.href = 'dark.css';
      toggleBtn.textContent = '切换浅色主题';
      localStorage.setItem('user-theme', 'dark');
    } else {
      // 切换为浅色主题
      styleEl.href = 'light.css';
      toggleBtn.textContent = '切换深色主题';
      localStorage.setItem('user-theme', 'light');
    }
  })
})

注意:多页面站点需要在每个页面都引入上述初始化JS逻辑,同域名下localStorage是全局共享的,可实现跨页面主题状态同步。如果你的站点是单页应用,只需要在入口文件引入一次即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 21:45:04