?> 背景知识::point_right: CSS_variables,var()
CSS变量类似于我们在SCSS、LESS中定义的变量,但前者支持通过JS来控制变量的值,以--
开头,(e.g. --main-color: #b4a078
),通过var(--main-color)
来引用。var()
函数接受两个参数(e.g. var(--main-color, gray)
),第一个参数为自定义属性名,第二个参数用作缺省值。
<script v-pre type="text/x-template" id="custom-variables"> <style> /* 全局 custom-variables */ /* :root { --r: 51; --g: 51; --b: 51; } */ main { width: 100%; padding: 60px 29px; display: flex; flex-direction: column; align-items: center; } label { display: flex; align-items: center; } input { padding: 0; width: 29px; height: 29px; } div.variables-block { width: 100%; display: flex; justify-content: center; margin-top: 29px; } /* 局部 custom-variables */ div.variables-block > div { --r: 51; --g: 51; --b: 51; } div.variables-block > div::after { content: ""; display: inline-block; width: 52px; height: 52px; background: rgb(var(--r), var(--g), var(--b)); } </style> 请选择主题色:以下示例演示了通过JS setProperty 方法改变CSS变量,从而控制元素甚至伪元素的样式~
!> 如需设置特定的值,直接修改示例中INITIAL_COLOR
的值即可,只支持支6位16进制的颜色格式。