我们都知道目前现代浏览器都已支持css3变量,写法如下:

:root {
  --color: red;
}

我们除了用css的作用域修改变量的值之外,还可以通过js的方法修改,方法如下:

let root = document.documentElement;

// 读取
let rootStyle = window.getComputedStyle(root);
let colorVar = rootStyle.getPropertyValue('--color').trim();
console.log(colorVar)

// 改变
root.style.setProperty('--color', 'blue')
console.log(colorVar)

// 删除
root.style.removeProperty('--color')
console.log(colorVar)