11 Star 37 Fork 20

Baryy / You-need-to-know-css

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
custom-variables.md 3.07 KB
一键复制 编辑 原始数据 按行查看 历史
宋慧武 提交于 2018-11-26 01:08 . :feat:add custom-variables

⚗️ 自定义变量

?> 背景知识::point_right: CSS_variablesvar()

CSS变量类似于我们在SCSS、LESS中定义的变量,但前者支持通过JS来控制变量的值,以--开头,(e.g. --main-color: #b4a078),通过var(--main-color)来引用。var()函数接受两个参数(e.g. var(--main-color, gray)),第一个参数为自定义属性名,第二个参数用作缺省值。

以下示例演示了通过JS setProperty 方法改变CSS变量,从而控制元素甚至伪元素的样式~

<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> 请选择主题色:
<script> const Color = require('./libs/color.js'); const INITIAL_COLOR = '#b4a078'; export default { data() { return { value: INITIAL_COLOR, } }, computed: { colorList() { const mainColor = this.value.length === 7 && this.value || INITIAL_COLOR; return this.getColorList(mainColor); } }, methods: { getColorList(val) { const color = Color(val); return Array.from({length: 10}).map((v, i) => { let rgb = color.mix(Color('white'), i / 10); this.$nextTick(() => { const style = this.$refs[`variable${i}`][0].style; style.setProperty('--r', rgb.red()); style.setProperty('--g', rgb.green()); style.setProperty('--b', rgb.blue()); }) }); } } } </script> </script>

!> 如需设置特定的值,直接修改示例中INITIAL_COLOR的值即可,只支持支6位16进制的颜色格式

浏览器支持

<iframe src="https://caniuse.bitsofco.de/embed/index.html?feat=css-variables&periods=future_1,current,past_1,past_2,past_3&accessible-colours=false" frameborder="0" width="100%" height="436px"></iframe>
CSS
1
https://gitee.com/lhammer/You-need-to-know-css.git
git@gitee.com:lhammer/You-need-to-know-css.git
lhammer
You-need-to-know-css
You-need-to-know-css
master

搜索帮助