必须通过 document.documentElement.style.setProperty 设置 CSS 自定义属性,主题配置应预存为对象并批量注入,切换后同步更新 data-theme 属性和 localStorage,注意兼容性与性能优化。
document.documentElement 设置 CSS 变量直接改 style 属性或操作 标签加载不同 CSS 文件,无法实现真正的“动态变量更新”。CSS 自定义属性(--color-bg 等)的作用域在 :root(即 document.documentElement),只有在这里设置,才
能让整个页面响应式重绘。
常见错误是写成 document.body.style.setProperty(...),这只会作用于 元素本身,子元素继承不到,或者继承但未触发重排重绘。
document.documentElement.style.setProperty('--color-bg', '#222')
document.querySelector('.theme-switcher').style 或操作内联 style 属性setProperty 不会覆盖旧值,而是叠加;清空某变量需设为 ''(空字符串)或重新赋默认值把深色/浅色主题的全部变量值写死在 if/else 里,后期维护痛苦、易出错、无法扩展。推荐用对象结构组织主题配置,再用一个函数批量注入。
例如:
const themes = {
light: {
'--color-bg': '#fff',
'--color-text': '#333',
'--color-border': '#eee'
},
dark: {
'--color-bg': '#1a1a1a',
'--color-text': '#f0f0f0',
'--color-border': '#333'
}
};
function applyTheme(themeKey) {
const theme = themes[themeKey];
if (!theme) return;
Object.entries(theme).forEach(([prop, value]) => {
document.documentElement.style.setProperty(prop, value);
});
}
-- 前缀)var(--color-bg) 这类引用,CSS 变量不支持 JS 对象内嵌套解析themes 改为从 localStorage 读取并合并默认值data-theme 属性和 localStorage仅改 CSS 变量不够。用户刷新页面后状态丢失,且某些组件(比如依赖 [data-theme="dark"] 的 CSS 选择器)需要 DOM 属性配合才能生效。
document.documentElement.setAttribute('data-theme', 'dark')
localStorage.setItem('ui-theme', 'dark')
const saved = localStorage.getItem('ui-theme') || 'light',再调用 applyTheme(saved)
localStorage 变化来触发主题更新——它只在其他 tab 触发,当前页需主动读取CSS 自定义属性在 IE 中完全不可用,如果项目还需兼容 IE,这套方案必须降级为 class 切换 + 多份 CSS 规则(如 .theme-dark .card { background: #111; })。
对于含 20+ 变量的主题,连续调用 setProperty 可能引发强制同步布局(layout thrashing),尤其在低端设备上卡顿。
Object.assign(document.documentElement.style, theme) 替代循环 setProperty(注意:此法仅适用于无连字符的属性名,CSS 变量仍需用 setProperty)requestAnimationFrame 批量更新,或先拼接 style 字符串再一次性 setAttributegetComputedStyle 在每次切换前读取旧值——完全没必要,也不影响新值生效