uniapp 横竖屏切换时 uview 自定义导航栏标题不居中
时间: 2023-10-07 11:05:21 浏览: 185
在uniapp中,当你切换横竖屏时,会导致页面重新渲染,此时你需要在页面生命周期的 `onResize` 方法中重新计算导航栏标题的位置,以保证其居中显示。
具体的实现方式如下:
1. 在 `onLoad` 生命周期中记录导航栏标题的初始位置
```javascript
onLoad() {
this.titleRect = uni.getMenuButtonBoundingClientRect()
}
```
2. 在 `onResize` 生命周期中重新计算导航栏标题的位置
```javascript
onResize() {
const { screenWidth } = uni.getSystemInfoSync()
const { left, width, height, top } = this.titleRect
const margin = (screenWidth - width) / 2 - left
this.titleStyle = `margin-left:${margin}px;width:${width}px;height:${height}px;top:${top}px;`
}
```
3. 在导航栏标题的绑定样式中使用 `titleStyle` 变量
```html
<view class="nav-title" :style="titleStyle">{{ title }}</view>
```
其中,`titleStyle` 是一个动态绑定的变量,其值会在 `onResize` 生命周期中重新计算。
以上是一种可能的解决方案,如果不行可以和我说一下具体情况,再看看有没有其他的解决方案。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)