微信小程序如何獲取元素的高度
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) }
PHP中文網(wǎng),大量免費小程序開發(fā)教程,歡迎學(xué)習(xí)!