原理:这是在没有设置自定义时的原生导航栏,我们发现整体的高度就是 (状态栏高度 + 导航栏高度)而状态栏高度可以通过 wx.getSystemInfo()获取,现在就只用解决导航栏高度了观察发现,胶囊顶部高度距导航栏顶部高度的高度差和胶囊底部高度距导航栏底部高度的高度差,是一样的也就是说 导航栏高度 = 胶囊高度 +(高度差)x 2 而胶囊信息可以通过 wx.getMenuButtonBoundingClientRect() 获取,现在就只用解决高度差了 wx.getMenuButtonBoundingClientRect() 中也返回了胶囊顶部距屏幕顶部距离的信息(top) 所以知 高度差 = 胶囊顶部距屏幕顶部距离 - 状态栏高度。
导航栏整体高度:
menu = wx.getMenuButtonBoundingClientRect()
system = wx.getSystemInfo
导航栏高度 = menu.statusBarHeight + menu.height + (menu.top - menu.statusBarHeight) * 2
到此我们就完美解决了导航栏高度的问题而导航栏内容就是内容标签的view高度等于menu.height并且垂直居中。
举个🌰子:
//app.js
onLaunch: function () {
//获取系统信息
wx.getSystemInfo({
success: res => {
this.system = res
}
})
//获取胶囊信息
this.menu = wx.getMenuButtonBoundingClientRect()
//打印数据
console.log('系统信息', this.system)
console.log('胶囊信息', this.menu)
}
//nav-bar.wxml
<view class='nav_box' style='background:{{navColor}};'>
<view style='height:{{s}}px' />
<view class='navBar' style='height:{{n}}px'>
<view class='content' style='height:{{h}}px'>
<!-- 导航自定义内容 -->
<!-- 1. 插槽 可在使用页面插入所需内容 -->
<slot></slot>
<!-- 2. 选择渲染 可在js页面 设置渲染type属性 不同场景传不同值 -->
<block wx:if='{{type == 0}}'>
导航一
</block>
<block wx:if='{{type == 1}}'>
<van-image width="{{s+5}}" height="{{s+3}}" src="https://fenghuangzhanhui-1303119254.file.myqcloud.com/upload/20211221/9a323431fd4341c18524de18595336e8.jpg" />
<view class="comtent-box">
这里可以写标题
</view>
</block>
<block wx:else>
导航三
</block>
</view>
</view>
</view>
<view style='height:{{s+n}}px' /> <!-- 注:占位用 -->
//nav-bar.js
//获取应用实例
const app = getApp()
Component({
/**
* 组件的属性列表
*/
properties: {
type:{
type:Number,
value:1
},
//导航栏颜色
navColor: {
type: String,
value: '#fff'
}
},
/**
* 组件的初始数据
*/
data: {
s: app.system.statusBarHeight, //状态栏高度
n: (app.menu.top - app.system.statusBarHeight) * 2 + app.menu.height+6, //导航栏高度
h: app.menu.height+6 //胶囊高度
}
})
//nav-bar.wxss
.nav_box {
position: fixed;
width: 100%;
font-size: 15px;
z-index: 999;
}
.navBar {
display: flex;
align-items: center;
padding: 0 10px;
}
.content {
width: 100%;
display: flex;
align-items: center;
/* background: green; */
}
.comtent-box{
margin-left: 5px;
/* width: 140px; */
/* border: 1px solid pink; */
font-size: 16px;
font-weight: 500;
}