小程序中使用css var變量(使js可以動態(tài)設(shè)置css樣式屬性)
使用sass,stylus可以很方便的使用變量來做樣式設(shè)計,其實css也同樣可以定義變量,在小程序中由于原生不支持動態(tài)css語法,so,可以使用css變量來使用開發(fā)工作變簡單。
基本用法
基礎(chǔ)用法
<!--web開發(fā)中頂層變量的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); }
提升用法
<div class="one"> <div class="two"> <div class="three"> </div> <div class="four"> </div> <div> </div>
.two { --test: 10px; } .three { --test: 2em; }
在這個例子中,var(--test)
的結(jié)果是:
- class="two" 對應(yīng)的節(jié)點: 10px
- class="three" 對應(yīng)的節(jié)點: element: 2em
- class="four" 對應(yīng)的節(jié)點: 10px (繼承自父級.two)
- class="one" 對應(yīng)的節(jié)點: 無效值, 即此屬性值為未被自定義css變量覆蓋的默認值
上述是一些基本概念,大致說明css變量的使用方法,注意在web開發(fā)中,我們使用:root
來設(shè)置頂層變量,更多詳細說明參考MDN的文檔
妙用css變量
開發(fā)中經(jīng)常遇到的問題是,css的數(shù)據(jù)是寫死的,不能夠和js變量直通,即有些數(shù)據(jù)使用動態(tài)變化的,但css用不了。對了,可以使用css變量試試呀
js
// 在js中設(shè)置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); } })
wxml
<!--將css變量(js中設(shè)置的那些)賦值給style--> <view class="container"> <view class="my-view" style="{{viewData.style}}"> <image src="/images/abc.png" mode="widthFix"/> </view> </view>
wxss
/* 使用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變量就可以動態(tài)設(shè)置css的屬性值
代碼片段
https://developers.weixin.qq.com/s/aWfUGCmG7Efe
小程序演示
到此這篇關(guān)于小程序中使用css var變量的文章就介紹到這了,更多相關(guān)小程序使用css var變量內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JavaScript中5個重要的Observer函數(shù)小結(jié)
瀏覽器為開發(fā)者提供了功能豐富的Observer,本文主要介紹了JavaScript中5個重要的Observer函數(shù)小結(jié),具有一定的參考價值,感興趣的可以了解一下2024-01-01