JavaScript通过style.setProperty()和getComputedStyle().getPropertyValue()操作CSS自定义属性实现动态主题切换,推荐挂载于:root并配合class切换与localStorage持久化。
JavaScript 可以通过 style.setProperty() 和 getComputedStyle().getPropertyValue() 直接读写 CSS 自定义属性(即 CSS 变量),这是实现动态主题切换最轻量、最推荐的方式。
把变量挂载在 :root 上,就能全局生效。JS 中用 document.documentElement.style 操作:
document.documentElement.style.setProperty('--primary-color', '#4a6fa5');
const theme = { '--primary-color': '#ff6b6b', '--bg-color': '#f8f9fa', '--text-color': '#333' };
Object.entries(theme).forEach(([prop, val]) => {
document.documentElement.style.setProperty(prop, val);
});--),且大小写敏感。用 getComputedStyle 从 :root 获取,返回的是计算后的字符串(含单位):
const color = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').
trim(); // → "#4a6fa5"
if (color === '#1a1a1a') { /* 深色主题逻辑 */ }
不推荐纯 JS 写死所有变量,更优雅的方式是预定义几套主题 class,在 CSS 中声明对应变量,JS 只负责切 class:
:root { --primary-color: #007bff; }
.theme-dark { --primary-color: #0056b3; --bg-color: #212529; }
.theme-high-contrast { --primary-color: #e60000; }document.documentElement.className = 'theme-dark'; 或 document.documentElement.classList.toggle('theme-dark');
把用户偏好存到 localStorage,页面加载时恢复:
localStorage.setItem('theme', 'theme-dark');
const savedTheme = localStorage.getItem('theme');
if (savedTheme && document.body.classList.contains(savedTheme)) {
document.documentElement.className = savedTheme;
}prefers-color-scheme)作为默认 fallback。基本上就这些。核心就三点:变量定义在 :root、JS 用 setProperty/getPropertyValue 操作、搭配 class + localStorage 做工程化管理。不复杂但容易忽略细节,比如变量名格式、trim 空格、CSS 作用域范围等。