在 JavaScript 中实现主题切换通常结合 CSS 和 DOM 操作,以下是常见的实现步骤:
一、基础实现方案
1. 定义 CSS 主题变量
使用 CSS 变量定义不同主题的样式:
/* 默认主题(亮色) */
:root {
--bg-color: #ffffff;
--text-color: #333333;
}
/* 暗色主题 */
[data-theme="dark"] {
--bg-color: #1a1a1a;
--text-color: #f0f0f0;
}
/* 应用变量 */
body {
background-color: var(--bg-color);
color: var(--text-color);
transition: background-color 0.3s, color 0.3s; /* 平滑过渡 */
}
2. HTML 添加切换按钮
<button id="theme-toggle">切换主题</button>
3. JavaScript 切换逻辑
const themeToggle = document.getElementById('theme-toggle');
// 切换主题函数
function toggleTheme() {
const html = document.documentElement;
const isDark = html.getAttribute('data-theme') === 'dark';
// 切换主题标记
html.setAttribute('data-theme', isDark ? 'light' : 'dark');
// 保存用户偏好(可选)
localStorage.setItem('theme', isDark ? 'light' : 'dark');
}
// 初始化主题(从 localStorage 读取)
const savedTheme = localStorage.getItem('theme');
if (savedTheme) {
document.documentElement.setAttribute('data-theme', savedTheme);
}
// 绑定点击事件
themeToggle.addEventListener('click', toggleTheme);
二、高级优化方案
1. 多主题支持
定义多个主题并通过循环切换:
const themes = ['light', 'dark', 'blue'];
let currentThemeIndex = 0;
function cycleThemes() {
currentThemeIndex = (currentThemeIndex + 1) % themes.length;
document.documentElement.setAttribute('data-theme', themes[currentThemeIndex]);
}
2. 跟随系统主题
监听系统主题变化:
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
const theme = e.matches ? 'dark' : 'light';
document.documentElement.setAttribute('data-theme', theme);
});
3. 使用 CSS 类名替代属性
如果更喜欢用类名:
.dark-theme {
--bg-color: #1a1a1a;
--text-color: #f0f0f0;
}
document.body.classList.toggle('dark-theme');
三、注意事项
- 持久化存储:使用
localStorage
保存用户选择,提升体验。 - 服务端渲染 (SSR):若需支持 SSR,可通过
<script>
在页面加载前读取存储的主题。 - 性能:避免频繁操作 DOM,复杂主题建议使用 CSS 变量而非全局类名覆盖。
你可以实现灵活的主题切换功能,并支持扩展更多自定义主题。