说明
- css变量只能以[–]开头。
- 距离当前dom元素层级最近的父元素作用域css变量的值更容易生效。
- css变量在css文件中只能以var()函数来使用。
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>css变量设置颜色</title>
</head>
<style>
:root {
--theRoot: rgb(255, 255, 0);
--fangBorder: rgb(255, 0, 0);
}
.myDiv {
--theDiv: rgb(0, 255, 0);
--fangBorder: rgb(0, 0, 255);
}
body {
background: var(--theRoot);
border: solid 5px var(--fangBorder);
}
.myDiv {
width: 100px;
height: 100px;
background: var(--theDiv);
border: solid 5px var(--fangBorder);
}
</style>
<body>
<div class="myDiv"></div>
</body>
<script>
setTimeout(() => {
let rootElement = document.querySelector(":root");
let rootStyles = getComputedStyle(rootElement);
let rootStyleValue = rootStyles.getPropertyValue("--fangBorder");
console.log("代码设置前: rootStyleValue--->", rootStyleValue);
rootElement.style.setProperty("--fangBorder", "rgb(0, 0, 0)");
rootStyleValue = rootStyles.getPropertyValue("--fangBorder");
console.log("代码设置后: rootStyleValue--->", rootStyleValue);
let thisElement = document.querySelectorAll(".myDiv")[0];
let thisStyles = getComputedStyle(thisElement);
let thisStyleValue = thisStyles.getPropertyValue("--fangBorder");
console.log("代码设置前: thisStyleValue--->", thisStyleValue);
thisElement.style.setProperty("--fangBorder", "rgb(255, 255, 255)");
thisStyleValue = thisStyles.getPropertyValue("--fangBorder");
console.log("代码设置后: thisStyleValue--->", thisStyleValue);
}, 3000);
</script>
</html>
来源:
- CSS 变量教程;
- CSS变量(自定义属性)实践指南;