微信小程序開發(fā)中想要如h5一樣獲取元素的寬高值進行業(yè)務的功能實現(xiàn),一開始不知道怎么實現(xiàn)踩萎,翻看文檔發(fā)現(xiàn),微信官方提供了一個非常好的東西
SelectorQuery wx.createSelectorQuery()
示例代碼
const query = wx.createSelectorQuery()
query.select('#the-id').boundingClientRect()
query.selectViewport().scrollOffset()
query.exec(function(res){
res[0].top // #the-id節(jié)點的上邊界坐標
res[1].scrollTop // 顯示區(qū)域的豎直滾動位置
})
1.如果高度要px單位的話:
let query = wx.createSelectorQuery();
query.select('.content').boundingClientRect(rect=>{
let height = rect.height;
console.log(height);
}).exec();
2.如果高度要rpx單位的話尿瞭,那么可以用寬高比換算獲得:(以下的750是該元素的寬度乾蛤,單位是rpx的)
let query = wx.createSelectorQuery();
query.select('.content').boundingClientRect(rect=>{
let clientHeight = rect.height;
let clientWidth = rect.width;
let ratio = 750 / clientWidth;
let height = clientHeight * ratio;
console.log(height);
}).exec();
3.在頁面渲染完成OnReady回調(diào) 獲取元素高度時,如果不加定時器日缨,獲取的元素的高度還是沒渲染完異步數(shù)據(jù)前的高度钱反。故需要加定時器
onReady () {
setTimeout(() => {
let query = wx.createSelectorQuery();
query.select('.content').boundingClientRect(rect=>{
let height = rect.height;
console.log(height);
}).exec();
}, 300)
}