在看本篇以前,期待讀者先了解js的document.querySelector 方法,在此不做贅述。
由於微信官方禁止小程序操作dom元素,因而無法像前端一樣操作小程序DOM,好在官方提供了API ,
這個api叫做 wx.createSelectorQuery(), 官方定義:返回一個 SelectorQuery 對象實例。
這個api的select()方法用於查找元素,類似jq的元素選擇器
爾后有boundingClientRect(function(res){})則返回指定元素的DOM屬性,res代表元素本身,(百度了boundingClientRect :邊界中心)
再之后的exec(function(rect){})則是設置元素屬性,rect在這里指的是所有匹配到結果的集合,通過調用that/this.setdata({})可以更改元素dom值,請注意!rect是一個數組集合,想要設置某一個元素,需要給該數組加指定元素的下標!
來個簡單demo:
wxml:
<swiper current="{{currentData}}" class='swiper' style="height:{{swiperHeight}}px;" duration="300" bindchange="bindchange"> <swiper-item> <view class="cont1">111</view> </swiper-item>
在這個demo里 我想獲取.cont1的高度從而動態調整swiper的高度,因而我給swiper的高度設置了參數swiperHeight
wx.js:
page({ data:{ swiperHeight:0 } , /*由於期待頁面加載完畢就顯示,所以我放在了onload函數內*/ /** * 生命周期函數--監聽頁面初次渲染完成 */ onReady: function () { var that = this const query = wx.createSelectorQuery(); query.select('.cont1').boundingClientRect(function (res) { //這里返回元素自身的DOM屬性 console.log(res); }).exec(function(rect){ that.setData({ swiperHeight: rect[0].height + 0 }) // rect返回一個數組,需要使用下標0才能找到 // console.log(s[0].height) }); }, })
網上聽大佬說偶爾會有rect返回為null的意外,昨晚翻遍百度,終於找到了一個解決方法,感謝那位大佬(傳送門)
/*原理是使用定時器異步獲取dom*/
setTimeout(function () { var query = wx.createSelectorQuery(); query.select('.cont1').boundingClientRect(); query.exec(function (rect) { if (rect === null) return; that.setData({ swiperHeight: rect .height + 10 }) }); }, 500)
如果有哪些錯誤,歡迎指教
以上。