uni-app boundingClientRect定位的top位置有误,前期隐藏page.json文件中globalStyle节点的navigationStyle=custom时出现问题
uni-app boundingClientRect定位的top位置有误,前期隐藏page.json文件中globalStyle节点的navigationStyle=custom时出现问题
示例代码:
uni.createSelectorQuery().select('*').boundingClientRect((data) => {
console.log(data.top);
}).exec();
操作步骤:
见描述
预期结果:
见描述
实际结果:
见描述
bug描述:
隐藏页面导航之后,获取html元素节点定位位置,的垂直位置出错
| 信息类别 | 详细信息 |
|----------------|------------------|
| 产品分类 | uniapp/App |
| PC开发环境操作系统 | Windows |
| PC开发环境操作系统版本号 | 10 |
| HBuilderX类型 | 正式 |
| HBuilderX版本号| 3.4.7 |
| 手机系统 | Android |
| 手机系统版本号 | Android 10 |
| 手机厂商 | 红米 |
| 手机机型 | k40 游戏增强版 |
| 页面类型 | vue |
| vue版本 | vue3 |
| 打包方式 | 云端 |
| 项目创建方式 | HBuilderX |



4 回复
没人处理这个问题吗
请提供简单可复现的最小示例(上传附件),方便我们快速排查问题哦。
【bug优先处理规则】https://ask.dcloud.net.cn/article/38139
可创建一个微信小程序原生示例,看看得到的结果是否一样
在 uni-app
中,使用 boundingClientRect
获取元素的位置信息时,如果 page.json
文件中的 globalStyle
节点设置了 navigationStyle: 'custom'
,可能会导致 top
位置计算不准确。这是因为 navigationStyle: 'custom'
会隐藏默认的导航栏,从而影响页面布局和元素的位置计算。
问题分析
-
navigationStyle: 'custom'
的影响:- 当
navigationStyle
设置为'custom'
时,页面顶部会没有默认的导航栏,这会导致页面的布局发生变化。 - 如果页面中有元素依赖于导航栏的高度进行定位,那么在隐藏导航栏后,这些元素的
top
值可能会发生变化。
- 当
-
boundingClientRect
的计算:boundingClientRect
返回的是元素相对于视口的位置信息。如果页面布局发生变化(如隐藏导航栏),元素的top
值也会相应变化。
解决方案
-
手动调整
top
值:- 如果你知道导航栏的高度,可以在获取
boundingClientRect
后,手动调整top
值。 - 例如,如果导航栏高度为
44px
,你可以将top
值减去44px
。
uni.createSelectorQuery().select('#elementId').boundingClientRect(data => { const navigationBarHeight = 44; // 假设导航栏高度为44px const adjustedTop = data.top - navigationBarHeight; console.log('Adjusted top:', adjustedTop); }).exec();
- 如果你知道导航栏的高度,可以在获取
-
动态获取导航栏高度:
- 如果你不确定导航栏的高度,可以通过
uni.getSystemInfoSync()
获取状态栏高度,然后加上导航栏的默认高度。
const systemInfo = uni.getSystemInfoSync(); const statusBarHeight = systemInfo.statusBarHeight; const navigationBarHeight = 44; // 默认导航栏高度 const totalHeight = statusBarHeight + navigationBarHeight; uni.createSelectorQuery().select('#elementId').boundingClientRect(data => { const adjustedTop = data.top - totalHeight; console.log('Adjusted top:', adjustedTop); }).exec();
- 如果你不确定导航栏的高度,可以通过
-
使用
page-meta
组件:- 如果你需要自定义导航栏,可以使用
page-meta
组件来设置页面的导航栏样式,而不是全局设置navigationStyle: 'custom'
。
<page-meta> <navigation-bar title="Custom Title" background-color="#ffffff" /> </page-meta>
- 如果你需要自定义导航栏,可以使用
-
避免全局设置
navigationStyle: 'custom'
:- 如果可能,尽量避免在
globalStyle
中全局设置navigationStyle: 'custom'
,而是在需要自定义导航栏的页面中单独设置。
{ "pages": [ { "path": "pages/index/index", "style": { "navigationStyle": "custom" } } ] }
- 如果可能,尽量避免在