通过CSS变量和JavaScript实现主题切换,首先定义:root中的主题变量,利用[data-theme]属性选择器覆盖样式,并通过JavaScript切换属性值实现手动换肤;结合prefers-color-scheme媒体查询可自动适配系统偏好;使用localStorage保存用户选择,确保刷新后主题不变;页面加载时优先读取本地存储或系统设置,保证体验一致。关键在于统一管理变量、同步状态与初始化逻辑。

通过 CSS 实现按条件切换主题,核心是利用 CSS 自定义属性(变量) 和 @media 查询或类切换 来动态改变页面样式。以下是几种常见且实用的方法:
1. 使用 CSS 自定义属性定义主题
在根元素上定义不同主题的变量,便于全局调用和切换。
:root {--bg-color: #fff;
--text-color: #333;
}
[data-theme="dark"] {
--bg-color: #1a1a1a;
--text-color: #f1f1f1;
}
然后在其他样式中使用这些变量:
body {background-color: var(--bg-color);
color: var(--text-color);
}
2. 通过 JavaScript 切换主题类
让用户手动切换主题,比如点击按钮从浅色变为深色。
立即学习“前端免费学习笔记(深入)”;
HTML 按钮示例:
JavaScript 控制 data-theme 属性:
const current = document.documentElement.getAttribute('data-theme');
const newTheme = current === 'dark' ? 'light' : 'dark';
document.documentElement.setAttribute('data-theme', newTheme);
}
页面加载时可读取用户偏好并设置初始主题。
3. 根据系统偏好自动适配(媒体查询)
使用 prefers-color-scheme 让页面默认匹配用户的系统设置。
:root {
--bg-color: #1a1a1a;
--text-color: #f1f1f1;
}
}
@media (prefers-color-scheme: light) {
:root {
--bg-color: #fff;
--text-color: #333;
}
}
这样无需 JS 就能实现自动暗黑模式,适合首次访问用户。
4. 结合本地存储记住用户选择
避免每次刷新都重置主题,把用户选择存入 localStorage。
// 页面加载时恢复主题const saved = localStorage.getItem('theme');
if (saved) {
document.documentElement.setAttribute('data-theme', saved);
}
// 切换时保存
function toggleTheme() {
const current = document.documentElement.getAttribute('data-theme');
const newTheme = current === 'dark' ? 'light' : 'dark';
document.documentElement.setAttribute('data-theme', newTheme);
localStorage.setItem('theme', newTheme);
}
基本上就这些。通过组合 CSS 变量、属性选择器、JS 控制和本地存储,可以灵活实现主题按条件切换。关键是结构清晰,变量统一管理,用户体验自然。不复杂但容易忽略细节,比如初始化和存储同步。










