手册
目录
收藏278
分享
阅读3019
更新时间2025-07-16
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 |
| 函数 | 描述 |
|---|---|
| var() | 插入 CSS 变量的值。 |
相关
视频
RELATED VIDEOS
科技资讯
1
2
3
4
5
6
7
8
9
精选课程
共5课时
17.2万人学习
共49课时
77.3万人学习
共29课时
61.9万人学习
共25课时
39.4万人学习
共43课时
71.2万人学习
共25课时
61.8万人学习
共22课时
23.1万人学习
共28课时
34万人学习
共89课时
125.6万人学习