getBoundingClientRectAsync数据不准在uni-app中
getBoundingClientRectAsync数据不准在uni-app中
示例代码:
获取方法
const stickyRect = await (this.$refs['refauthore'] as UniElement).getBoundingClientRectAsync()!;
console.log('--------------', stickyRect)
const stickyRect1 = await (this.$refs['reftags'] as UniElement).getBoundingClientRectAsync()!;
console.log('==================', stickyRect1)
自定义控件的结构如上图
操作步骤:
嵌套循环外层是scroll-view 内层是list-view 内层的list-view写成了自定义组件 然后在自定义组件里面获取某个view的位置 信息时出错 只能获取自定义组件里面的第一个元素位置 信息正确 其它的都不行
预期结果:
top bottom返回的值应该不大于550(外层的scrollview上面是个图片 图片高度是487) 而且明显的BUG 如果reftag不设置margin 宽度不是10% 获取出来的结果居然right也是0 一眼BUG呀
实际结果:
组件中的第一个元素top是521 那么下面这个也不会超过550 应该在530左右 但现在出现了一千多的值
bug描述:
23:01:57.594 -------------- [io.dcloud.uniapp.runtime.DOMRect] {bottom: 580, height: 59, left: 13, right: 13, top: 521, …} at uni_modules/pf-commentlist/components/pf-commentlist/pf-commentlist.vue:246 23:01:57.594 子滚动 at uni_modules/pf-commentlist/components/pf-commentlist/pf-commentlist.vue:256 23:01:57.604 ================== [io.dcloud.uniapp.runtime.DOMRect] {bottom: 1521.3892822265625, height: 2, left: 8.854961395263672, right: 8.854961395263672, top: 1519.3892822265625, …} at uni_modules/pf-commentlist/components/pf-commentlist/pf-commentlist.vue:248
手机屏没有这么长 为什么会出来1521的数
开发环境 | 版本号 | 项目创建方式 |
---|---|---|
Windows | win10 专业版 | HBuilderX |
手机系统 | Android 13 | HBuilderX |
手机厂商 | 华为 | |
手机机型 | 荣耀100 | |
HBuilderX类型 | 正式 | |
HBuilderX版本号 | 4.57 | |
页面类型 | vue | |
vue版本 | vue3 | |
打包方式 | 云端 |
更多关于getBoundingClientRectAsync数据不准在uni-app中的实战教程也可以访问 https://www.itying.com/category-93-b0.html
更多关于getBoundingClientRectAsync数据不准在uni-app中的实战教程也可以访问 https://www.itying.com/category-93-b0.html
这是一个典型的uni-app中getBoundingClientRectAsync在嵌套滚动容器中测量位置不准确的问题。主要原因如下:
-
在嵌套的scroll-view和list-view结构中,getBoundingClientRectAsync返回的是元素相对于视口的绝对位置,而不是相对于父容器的位置。
-
当元素位于可滚动容器内时,如果容器发生了滚动,getBoundingClientRectAsync返回的top值会包含滚动偏移量,导致数值偏大。
解决方案建议:
- 对于嵌套滚动容器中的元素测量,建议使用uni.createSelectorQuery()替代getBoundingClientRectAsync:
const query = uni.createSelectorQuery().in(this)
query.select('#yourElement').boundingClientRect(data => {
console.log(data)
}).exec()