uniapp動態修改元素節點樣式詳解
阿新 • • 發佈:2021-08-22
目錄
- 一,通過style屬性繫結來修改
- html:
- 對應的:
- 實現的效果:
- 二,利用ref來獲取dom元素節點
- 程式碼:
- 實現的效果:
- 總結
一,通過style屬性繫結來修改
第一步:肯定是需要獲取元素節點
在uniApp專案中沒有windouw物件,所以通過document不能直接獲取dom節點,的refs只對自定義元件有效,對uniapp中的標籤不生效。
檢視uniapp官網有一個uni.createSelectorQuery() API;可以通過這個屬性獲取標籤的樣式,在通過動態繫結樣式來修改;
html:
<button type="default" @click="handleFont">點選增大字型</button> <view class="weibo_box"www.cppcns.comid='index0' :style="{fontSize:vHeight + 'px'}">
對應的js:
data(){ return { vHeight:22 } },handleFont(){ const that=this uni.createSelectorQuery().select('#index0').boundingClientRect(function (data) { console.log('元素資訊0:',data) that.vHeight +=10 }).exec() }
實現的效果:
二,利用ref來獲取dom元素節點
程式碼:
<button type="default" @click="handlhttp://www.cppcns.comeFont">點選增大字型</button>
<view class="weibo_box" id='index1' ref="mydom">
第二個
</view>
data(){ return { vHeight:22 } },//部分程式碼不相關,省略 handleFont(){ const that=this that.$refs.mydom.$el.style.fontSize=that.vwww.cppcns.comHeight+=1+'px' }
實現的效果:
總結
本篇文章就到這裡了,希望能給你帶來幫助,也希望您能夠多多關注我們的更多內容!