微信小程序中如何准确获取指定元素的高度值?
- 内容介绍
- 文章标签
- 相关推荐
本文共计373个文字,预计阅读时间需要2分钟。
微信小程序如何获取元素的尺寸:
1. 使用`wx.createSelectorQuery()`创建一个查询器实例。
2.选择需要查询的元素。
3.使用`.boundingClientRect()`获取元素的尺寸信息。
4.执行查询获取结果。
代码示例:
javascriptlet query=wx.createSelectorQuery();query.select('.content').boundingClientRect((rect)=> { let height=rect.height; console.log(height);}).exec();微信小程序如何获取元素的高度
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回调,获取元素高度时,如果不加定时器,获取的元素的高度还是没渲染完异步数据前的高度。故需要加定时器
onReady () { setTimeout(() => { let query = wx.createSelectorQuery(); query.select('.content').boundingClientRect(rect=>{ let height = rect.height; console.log(height); }).exec(); }, 300) }
PHP中文网,大量免费小程序开发教程,欢迎学习!
以上就是微信小程序如何获取元素的高度的详细内容,更多请关注自由互联其它相关文章!
本文共计373个文字,预计阅读时间需要2分钟。
微信小程序如何获取元素的尺寸:
1. 使用`wx.createSelectorQuery()`创建一个查询器实例。
2.选择需要查询的元素。
3.使用`.boundingClientRect()`获取元素的尺寸信息。
4.执行查询获取结果。
代码示例:
javascriptlet query=wx.createSelectorQuery();query.select('.content').boundingClientRect((rect)=> { let height=rect.height; console.log(height);}).exec();微信小程序如何获取元素的高度
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回调,获取元素高度时,如果不加定时器,获取的元素的高度还是没渲染完异步数据前的高度。故需要加定时器
onReady () { setTimeout(() => { let query = wx.createSelectorQuery(); query.select('.content').boundingClientRect(rect=>{ let height = rect.height; console.log(height); }).exec(); }, 300) }
PHP中文网,大量免费小程序开发教程,欢迎学习!
以上就是微信小程序如何获取元素的高度的详细内容,更多请关注自由互联其它相关文章!

