微信小程序 獲取元素高度(獲取元素節點信息)

1.若是高度要px單位的話:異步

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

2.若是高度要rpx單位的話,那麼能夠用寬高比換算得到:(如下的750是該元素的寬度,單位是rpx的)code

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回調 獲取元素高度時,若是不加定時器,獲取的元素的高度仍是沒渲染完異步數據前的高度。故須要加定時器io

onReady () {
	setTimeout(() => {
	let query = wx.createSelectorQuery();
	query.select('.content').boundingClientRect(rect=>{
		let height = rect.height;
		console.log(height);
		}).exec();
	}, 300)
}
相關文章
相關標籤/搜索