使用sass,stylus能够很方便的使用变量来作样式设计,其实css也一样能够定义变量,在小程序中因为原生不支持动态css语法,so,能够使用css变量来使用开发工做变简单。css
基础用法html
<!--web开发中顶层变量的key名是:root,小程序使用page--> page { --main-bg-color: brown; } .one { color: white; background-color: var(--main-bg-color); margin: 10px; } .two { color: white; background-color: black; margin: 10px; } .three { color: white; background-color: var(--main-bg-color); }
提高用法git
<div class="one"> <div class="two"> <div class="three"> </div> <div class="four"> </div> <div> </div>
.two { --test: 10px; } .three { --test: 2em; }
在这个例子中,var(--test)
的结果是:github
class="two" 对应的节点: 10px
class="three" 对应的节点: element: 2em
class="four" 对应的节点: 10px (继承自父级.two)
class="one" 对应的节点: 无效值, 即此属性值为未被自定义css变量覆盖的默认值 web
上述是一些基本概念,大体说明css变量的使用方法,注意在web开发中,咱们使用:root
来设置顶层变量,更多详细说明参考MDN的 文档小程序
开发中常常遇到的问题是,css的数据是写死的,不可以和js变量直通,即有些数据使用动态变化的,但css用不了。对了,能够使用css变量试试呀sass
// 在js中设置css变量 let myStyle = ` --bg-color:red; --border-radius:50%; --wid:200px; --hgt:200px; ` let chageStyle = ` --bg-color:red; --border-radius:50%; --wid:300px; --hgt:300px; ` Page({ data: { viewData: { style: myStyle } }, onLoad(){ setTimeout(() => { this.setData({'viewData.style': chageStyle}) }, 2000); } })
<!--将css变量(js中设置的那些)赋值给style--> <view class="container"> <view class="my-view" style="{{viewData.style}}"> <image src="/images/abc.png" mode="widthFix"/> </view> </view>
/* 使用var */ .my-view{ width: var(--wid); height: var(--hgt); border-radius: var(--border-radius); padding: 10px; box-sizing: border-box; background-color: var(--bg-color); transition: all 0.3s ease-in; } .my-view image{ width: 100%; height: 100%; border-radius: var(--border-radius); }
经过css变量就能够动态设置css的属性值xss
https://developers.weixin.qq....this