沉浸式导航头
要用自定义的导航栏首先需要将页面设置成沉浸式导航,在该页面的json文件中配置navigationStyle,如果是所有页面都需要沉浸式,则在app.json中设置
{"navigationBarTitleText": "测试","navigationStyle": "custom" // 沉浸式导航头}
创建组件目录
navigationBar.wxml文件:
<view class='nav-wrap' style='top: {{top}}rpx; height: {{height}}rpx; line-height: {{height}}rpx'> //top是右侧胶囊菜单距离手机顶部的距离 height是胶囊菜单的高度,可以设置导航与胶囊菜单同高<view class='nav-title' style='width: {{left - 36}}rpx'> // left是除去胶囊菜单所剩的宽度,36是图上返回图标的宽度,可自行修改<image class='nav-title-back' src="../../image/back.png" wx:if="{{showBack}}" catchtap="goBack"></image><view class='nav-title-text'>{{title}}</view></view></view>
navigationBar.wxss文件:
.nav-wrap {position: fixed;width: 100%;background: transparent;z-index: 9999999;}.nav-title {padding-left: 16px;display: flex;flex-direction: row;align-items:center;}.nav-title-back {width: 32rpx;height: 32rpx;flex: 0 0 32rpx;margin-right: 4rpx;}.nav-title-text {flex: 1 1 auto;font-size: 34rpx;color: #fff;font-weight: bold;}
navigationBar.json文件(组件必须):
{"component": true}
navigationBar.js文件:
Component({properties: {title: {type: String,value: true},showBack: {type: Boolean,value: true}},data: {top: 0,left: 0,height: 0,},lifetimes: {attached: function() {// 在组件实例进入页面节点树时执行wx.getSystemInfo({success: (res) => {const ratio = 750 / res.windowWidthconst menuInfo = wx.getMenuButtonBoundingClientRect();this.setData({top: menuInfo.top * ratio ,left: menuInfo.left * ratio , height: menuInfo.height * ratio ,})}})},},methods: {goBack() {if (this.properties.showBack) {wx.navigateBack()}},}});
在微信小程序页面中引用
页面文件夹index.wxml文件:
<navigation-bar title="自定义导航头" showBack="{{true}}"></navigation-bar> // title是标题,showBack是是否需要显示返回按钮
index.json文件:
{"navigationBarTitleText": "测试","usingComponents": {"navigation-bar": "../../components/navigationBar/navigationBar"},"navigationStyle": "custom" // 沉浸式导航头}
此外,若遇到胶囊信息报错或者获取不到,请查看兼容方法