uni-app uni.setNavigationBarColor 设置背景色时 H5 样式没有居中
uni-app uni.setNavigationBarColor 设置背景色时 H5 样式没有居中
示例代码:
setTimeout(() => {
uni.setNavigationBarColor({
frontColor: '#ffffff',
backgroundColor: this.topBackgroundColor,
animation: {
duration: 80,
timingFunc: 'easeIn'
}
})
}, 200)
操作步骤:
根据接口返回的背景色,在onShow() {
setTimeout(() => {
uni.setNavigationBarColor({
frontColor: '#ffffff',
backgroundColor: this.topBackgroundColor,
animation: {
duration: 80,
timingFunc: 'easeIn'
}
})
}, 200)
},
预期结果:
H5导航栏返回箭头垂直居中
实际结果:
没有垂直居中
bug描述:
单纯根据接口返回的背景色,动态设置背景色,H5返回箭头不是垂直居中,偏上
| 信息类别 | 信息内容 |
|----------------|--------------------|
| 产品分类 | uniapp/H5 |
| PC开发环境操作系统 | Mac |
| PC开发环境操作系统版本号 | 11.5.2 |
| HBuilderX类型 | 正式 |
| HBuilderX版本号 | 3.4.7 |
| 浏览器平台 | Chrome |
| 浏览器版本 | 100.0.4896.127 |
| 项目创建方式 | HBuilderX |
4 回复
截图,调试,看nav的高度 和 箭头距离上边的高
提供可以复现的demo
在 Uni-App 中,使用 uni.setNavigationBarColor
设置导航栏背景色时,H5 平台可能会出现样式没有居中的问题。这是因为 H5 平台的导航栏实现方式与小程序、App 平台不同,导致样式表现不一致。
解决方案
1. 自定义导航栏
如果 uni.setNavigationBarColor
在 H5 平台无法满足需求,可以考虑使用自定义导航栏。通过自定义导航栏,你可以完全控制导航栏的样式和布局。
步骤:
-
禁用原生导航栏 在
pages.json
中禁用原生导航栏:{ "path": "pages/index/index", "style": { "navigationBarTitleText": "首页", "navigationStyle": "custom" } }
-
创建自定义导航栏组件 创建一个自定义导航栏组件,例如
custom-navbar.vue
:<template> <view class="custom-navbar"> <view class="navbar-title">标题</view> </view> </template> <script> export default { name: 'CustomNavbar' } </script> <style> .custom-navbar { height: 44px; display: flex; align-items: center; justify-content: center; background-color: #007AFF; /* 设置背景色 */ color: #fff; /* 设置文字颜色 */ } .navbar-title { font-size: 16px; } </style>
-
在页面中使用自定义导航栏 在需要使用自定义导航栏的页面中引入并使用该组件:
<template> <view> <custom-navbar /> <!-- 页面内容 --> </view> </template> <script> import CustomNavbar from '@/components/custom-navbar.vue' export default { components: { CustomNavbar } } </script>
2. 使用 CSS 调整样式
如果你仍然想使用 uni.setNavigationBarColor
并且只是希望在 H5 平台上调整样式,可以通过 CSS 来微调导航栏的样式。
步骤:
-
在
App.vue
中全局设置样式 在App.vue
中全局设置导航栏的样式:<style> /* 针对 H5 平台的导航栏样式调整 */ .uni-page-head { display: flex; align-items: center; justify-content: center; } </style>
-
在页面中动态设置导航栏颜色 在页面中动态设置导航栏颜色:
export default { onLoad() { uni.setNavigationBarColor({ frontColor: '#ffffff', // 前景色 backgroundColor: '#007AFF' // 背景色 }); } }