js 实现更换主题
使用 CSS 变量实现主题切换
通过定义 CSS 变量并在 JavaScript 中动态修改这些变量,可以实现主题切换功能。CSS 变量通常定义在 :root 选择器中,以便全局访问。
:root {
--primary-color: #3498db;
--background-color: #ffffff;
--text-color: #333333;
}
.dark-theme {
--primary-color: #9b59b6;
--background-color: #2c3e50;
--text-color: #ecf0f1;
}
function toggleTheme() {
document.body.classList.toggle('dark-theme');
const theme = document.body.classList.contains('dark-theme') ? 'dark' : 'light';
localStorage.setItem('theme', theme);
}
// 初始化时检查本地存储的主题偏好
const savedTheme = localStorage.getItem('theme');
if (savedTheme === 'dark') {
document.body.classList.add('dark-theme');
}
通过切换类名实现主题
定义不同主题的 CSS 类,然后通过 JavaScript 切换这些类来实现主题变化。
.light-theme {
background-color: white;
color: black;
}
.dark-theme {
background-color: #222;
color: white;
}
const themeToggle = document.getElementById('theme-toggle');
themeToggle.addEventListener('click', () => {
document.body.classList.toggle('dark-theme');
document.body.classList.toggle('light-theme');
});
使用媒体查询同步系统主题
结合 prefers-color-scheme 媒体查询和 JavaScript,可以实现与系统主题同步的功能。
// 检测系统主题偏好
const systemPrefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
// 设置初始主题
if (systemPrefersDark) {
document.body.classList.add('dark-theme');
}
// 监听系统主题变化
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
if (e.matches) {
document.body.classList.add('dark-theme');
} else {
document.body.classList.remove('dark-theme');
}
});
使用第三方库实现主题切换
对于更复杂的主题需求,可以考虑使用专门的库如 theme-switcher 或 darkmode.js。
// 使用 darkmode.js 的示例
const options = {
bottom: '64px',
right: '32px',
time: '0.5s',
mixColor: '#fff',
backgroundColor: '#fff',
buttonColorDark: '#100f2c',
buttonColorLight: '#fff',
saveInCookies: true,
label: '🌓'
};
const darkmode = new Darkmode(options);
darkmode.showWidget();
主题切换的最佳实践
持久化用户选择:将用户选择的主题保存在 localStorage 或 cookie 中,以便下次访问时保持一致性。
添加过渡效果:为主题切换添加 CSS 过渡效果,使变化更平滑。
body {
transition: background-color 0.3s ease, color 0.3s ease;
}
无障碍考虑:确保主题切换不会影响内容的可读性,并为切换按钮添加适当的 ARIA 标签。

<button id="theme-toggle" aria-label="Toggle dark mode">Toggle Theme</button>






