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.0 15.0 31.0 9.1 36.0

CSS var() 函數

函數 描述
var() 插入 CSS 變量的值。