小程式中使用css var變數(使js可以動態設定css樣式屬性)
阿新 • • 發佈:2020-04-03
使用sass,stylus可以很方便的使用變數來做樣式設計,其實css也同樣可以定義變數,在小程式中由於原生不支援動態css語法,so,可以使用css變數來使用開發工作變簡單。
基本用法
基礎用法
<!--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); }
提升用法
<div class="one"> <div class="two"> <div class="three"> </div> <div class="four"> </div> <div> </div>
.two { --test: 10px; } .three { --test: 2em; }
在這個例子中,var(--test)
的結果是:
- class="two" 對應的節點: 10px
- class="three" 對應的節點: element: 2em
- class="four" 對應的節點: 10px (繼承自父級.two)
- class="one" 對應的節點: 無效值,即此屬性值為未被自定義css變數覆蓋的預設值
上述是一些基本概念,大致說明css變數的使用方法,注意在web開發中,我們使用:root
來設定頂層變數,更多詳細說明參考MDN的文件
妙用css變數
開發中經常遇到的問題是,css的資料是寫死的,不能夠和js變數直通,即有些資料使用動態變化的,但css用不了。對了,可以使用css變數試試呀
js
// 在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); } })
wxml
<!--將css變數(js中設定的那些)賦值給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變數就可以動態設定css的屬性值
程式碼片段
https://developers.weixin.qq.com/s/aWfUGCmG7Efe
github
小程式演示
到此這篇關於小程式中使用css var變數的文章就介紹到這了,更多相關小程式使用css var變數內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!