注意screenHeight屏高:屏幕高度 = 原生NavigationBar高度(含状态栏高度)+ 可使用窗口高度 + 原生TabBar高度
但是自定义导航栏screenHeight=windowHeight
由于是自定义导航栏无法获取原生NavigationBar高度,需要手动计算。
首先先获取状态栏高度和右上角胶囊的布局位置信息:
分别是uni.getSystemInfo()
获取系统信息以及uni.getMenuButtonBoundingClientRect
(这个函数h5环境下不能用要使用条件编译)
胶囊的顶部坐标是相对于屏幕,则由上图可知,标题栏高度 = (胶囊的顶部坐标 - 信号栏高度 )* 2 + 胶囊高度
最终代码
data() {
return {
menuButtonInfo:0,//胶囊按钮信息
statusBarHeight:0,//状态栏高度
musicheadHeight:0
};
},
onReady() {
// #ifdef MP-WEIXIN
//获取状态栏高度
const { statusBarHeight,windowHeight,screenHeight }= uni.getSystemInfoSync()
this.statusBarHeight=statusBarHeight
// 获取胶囊按钮信息(width、height、top等)
const {width,height,top}=uni.getMenuButtonBoundingClientRect()
this.menuButtonInfo={width,height,top}
// 胶囊按钮相对于离导航栏的上边距
const topDistance=this.menuButtonInfo.top-this.statusBarHeight;
// 计算导航栏高度
this.musicheadHeight=this.menuButtonInfo.height+topDistance*2;
// #endif
},
布局时使用status_bar占位块代替状态栏,不然后面用line-height设置标题居中有点麻烦,而且不可以使用height: var(–status-bar-height)设置状态栏高度(这个好像是固定的25px,而刘海屏已经不是25px了),必须动态设置。
<view class="musichead">
<view class="status_bar" :style="{'height':statusBarHeight+'px'}"></view>
<!-- #ifdef MP-WEIXIN -->
<view class="musicheadWEIXIN" :style="{
'height':musicheadHeight+'px',
'line-height': musicheadHeight+'px'
}">
<!-- 左边按钮 -->
<view class="btn" :style="{
'width':menuButtonInfo.width+'px',
'height':menuButtonInfo.height+'px',
'line-height':menuButtonInfo.height+'px',
'top':(menuButtonInfo.top)+'px'
}"
>
<view class="iconfont icon-zuojiantou"></view>
<view class="split_line">|</view>
<view class="iconfont icon-shouye"></view>
</view>
<!-- 标题 -->
<text class="title">{{title}}</text>
</view>
<!-- #endif -->
</view>
.musicheadWEIXIN{
width: 100%;
padding: 0;
margin: 0;
text-align: center;
}
.status_bar {
// height: var(--status-bar-height);
width: 100%;
}
.btn{
position: absolute;
display: flex;
box-sizing: border-box;
padding: 0;
margin: 0;
justify-content: space-around;
border: 1px solid #dcdcdc;
border-radius: 20px;
left:10px;
background-color: #fff;
.split_line{
color: #ffe8e8;
}
}
最终结果