:root的CSS变量必须用document.documentElement.style.setProperty()设置,漏掉documentElement或写错变量名(如缺--、拼接错误)、值不带单位均导致静默失效;读取全局变量须用getComputedStyle(document.documentElement);高频修改应批量操作防卡顿。

怎么改:root里定义的CSS变量
必须用 document.documentElement.style.setProperty(),不是 document.body 或随便一个元素。漏掉 documentElement 就等于没改——页面不会变,也不会报错,静默失败。
常见错误包括:
- 写成
document.body.style.setProperty('--color', 'red')—— body 不是 :root,改了也白改 - 变量名漏掉双短横,比如
setProperty('primary-color', 'red')→ 应该是'--primary-color' - 值没加引号,比如
setProperty('--font-size', 14)→ 浏览器会转成"14",但某些单位(如rem、px)必须显式带单位字符串,否则无效
读取时为什么拿不到:root的值
用 getComputedStyle(el).getPropertyValue('--var') 读某个元素上的变量,只返回它自己或祖先链上**显式设置过**的值,不会自动向上查找 :root。想读全局变量,目标必须是 document.documentElement。
例如:
立即学习“前端免费学习笔记(深入)”;
使用 JSON Schema 验证 JSON 数据,从示例 JSON 生成 schema,并将其转换为 TypeScript 接口、Python 数据类或 Markdown 文档。
const rootStyles = getComputedStyle(document.documentElement);
const theme = rootStyles.getPropertyValue('--theme'); // ✅ 正确
const theme2 = getComputedStyle(someDiv).getPropertyValue('--theme'); // ❌ someDiv 没设过 --theme,返回空字符串
注意:getPropertyValue() 返回恒为字符串,未定义时是 ""(空字符串),不是 undefined 或 null,别用 == null 判空。
批量修改变量时性能容易崩
在 scroll、resize 或动画帧里反复调用 setProperty(),会触发频繁的样式重计算(style recalc),浏览器来不及合并,页面明显卡顿。
实操建议:
- 高频场景下,先收集所有要改的键值对,再用一次循环统一设置,避免重复调用
- 不要在 for 循环中对同一个元素反复设同一变量,可用
Map缓存已设置过的[el, varName]组合 - 真需要强制同步布局(如旧版 Safari),可用
el.offsetHeight触发,但这是兜底手段,别滥用
动态拼接变量名容易写错字符串
比如想根据索引生成 --item-delay-1、--item-delay-2,常见错误是字符串拼接混乱:
// ❌ 错误:引号位置错,i 不会被求值
el.style.setProperty('--item-delay-" + i + "', '0.5s');
// ✅ 正确:用模板字面量最安全
el.style.setProperty(`--item-delay-${i}`, '0.5s');
// ✅ 或传统拼接(注意引号闭合)
el.style.setProperty('--item-delay-' + i, '0.5s');
拼错的结果不是报错,而是变量名变成字面量(比如 --item-delay-i),后续 var(--item-delay-i) 查不到值,样式不生效——这种 bug 极难定位。

















