微信小程序如何获取元素的高度

1、获取元素的高度(px单位):

1
2
3
4
5
let query = wx.createSelectorQuery();
query.select('.content').boundingClientRect(rect=>{
let height = rect.height;
console.log(height);
}).exec();

2、获取元素的高度(rpx单位),使用宽高比换算获得:(以下的750是该元素的宽度,单位是rpx的)

1
2
3
4
5
6
7
8
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回调,获取元素高度时,如果不加定时器,获取的元素的高度还是没渲染完异步数据前的高度。故需要加定时器

1
2
3
4
5
6
7
8
9
onReady () {
setTimeout(() => {
let query = wx.createSelectorQuery();
query.select('.content').boundingClientRect(rect=>{
let height = rect.height;
console.log(height);
}).exec();
}, 300)
}