目录

CSS 使用 JavaScript 更改变量


使用 JavaScript 更改变量

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

以下示例说明了如何创建脚本来显示和更改前几页中使用的示例中的 --blue 变量。现在,如果您不熟悉 JavaScript,请不要担心。您可以在我们的网站中了解有关 JavaScript 的更多信息JavaScript 教程

示例

<script>
// Get the root element
var r = document.querySelector(':root');

// Create a function for getting a variable value
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'));
}

// Create a function for setting a variable value
function myFunction_set() {
  // Set the value of variable --blue to another value (in this case "lightblue")
  r.style.setProperty('--blue', 'lightblue');
}
</script>
亲自试一试 »

浏览器支持

表中的数字指定第一个完全支持的浏览器版本var()函数。

Function
var() 49.0 15.0 31.0 9.1 36.0

CSS var() 函数

Property Description
var() Inserts the value of a CSS variable