一,分析需求与获取设备信息
小程序本身具有导航栏,但是有时我们需要自定义页面上半部分,就需要隐藏默认的导航栏,然后自己实现导航栏的个性化功能。
首先需要获取到设备本身的状态栏和胶囊的信息
getSystemInfoSync方法可以获取到设备的状态栏高度
getMenuButtonBoundingClientRect方法可以获取到胶囊的信息
上图黑色横线区分导航部分与页面内容部分;红色框圈出设备状态栏;绿色竖线是胶囊距离设备边缘的top值;紫色竖线为胶囊的高;粉色竖线是我们需要自定义导航的真实高;浅蓝色短竖线是胶囊距离页面内容的间隙宽度,这个宽度即为menuButton.top - systemInfo.statusBarHeight。信息收集完毕,接下来就是代码计算各个值:
// 获取设备导航栏信息
setNavBar(){
const systemInfo = wx.getSystemInfoSync();
console.log(systemInfo,"====systemInfo=====")
// 获取胶囊按钮位置信息
const menuButtonInfo = wx.getMenuButtonBoundingClientRect()
console.log(menuButtonInfo,"====menuButtonInfo=====")
this.globalData.navBarHeight = (menuButtonInfo.top - systemInfo.statusBarHeight) * 2 + menuButtonInfo.height + systemInfo.statusBarHeight;
this.globalData.menuButton = menuButtonInfo.top - systemInfo.statusBarHeight;
this.globalData.menuRight = systemInfo.screenWidth - menuButtonInfo.right;
this.globalData.menuHeight = menuButtonInfo.height;
}
二,项目配置
自定义导航栏,只需要在需要的页面json文件中配置字段 navigationStyle为 custom。
这里将其封装成组件,因此还需要在components文件夹中新增 navigation组件文件夹
三,实现代码
<view class="navigation" style="height:{{navBarHeight}}px;">
<view class="navigation-main">
<view
class="navigation-box"
style="height:{{menuHeight}}px; min-height:{{menuHeight}}px; line-height:{{menuHeight}}px; bottom:{{menuButton}}px;"
>
<!-- 导航内容区域 -->
<slot></slot>
</view>
</view>
</view>
.navigation{
position: fixed;
top: 0;
left: 0;
width: 100vw;
background:transparent;
z-index: 9999;
}
.navigation-main{
position: relative;
width: 100%;
height: 100%;
}
.navigation-box{
position: absolute;
box-sizing: border-box;
width: 100%;
}
.navigation-padding{
position: relative;
width: 100%;
}
在需要使用自定义导航栏的页面引入组件后,直接使用即可
<navigation>
<view wx:if="{{ isDevice && isLogin }}" class="f-bold f-16" style="text-align: center;">
自定义导航栏标题
</view>
</navigation>