CSS 变量 - JavaScript

CSS 使用 JavaScript 更改变量

使用 JavaScript 更改变量

CSS 变量可以访问 DOM,这意味着您可以通过 JavaScript 更改它们。

这个例子说明了如何创建脚本来显示并更改上一页中使用的示例中的 --blue 变量。此刻,如果您不熟悉 JavaScript,不要担心。您可以在我们的 JavaScript 教程中学到有关 JavaScript 的更多知识:

实例

<script>// 获取根元素var r = document.querySelector(':root');// 创建获取变量值的函数function myFunction_get() {  // Get the styles (properties and values) for the root  var rs = getComputedStyle(r);  // Alert the value of the --blue variable  alert("The value of --blue is: " + rs.getPropertyValue('--blue'));}// 创建设置变量值的函数function myFunction_set() {  // Set the value of variable --blue to another value (in this case "lightblue")  r.style.setProperty('--blue', 'lightblue');}</script>

亲自试一试

浏览器支持

表格中的数字注明了完全支持该属性的首个浏览器版本。

函数
var()49.015.031.09.136.0

CSS var() 函数

函数描述
var()插入 CSS 变量的值。