1. 设置全局取自定义表头样式
在app.json中添加 "navigationStyle": "custom"
"window": { "backgroundTextStyle": "light", "navigationBarBackgroundColor": "#fff", "navigationBarTitleText": "WeChat", "navigationBarTextStyle": "black", "navigationStyle": "custom"}
局部在每个页面index.json中添加"navigationStyle": "custom"
{ "usingComponents": { }, "navigationStyle": "custom"}
2. 在app.js 小程序入口文件中配置
在app.js 获取系统信息、胶囊按钮位置信息来配置导航高度。 后面导航需要用到
App({ onLaunch: function () { this.getBasicInfo() }, getBasicInfo(){ // 获取系统信息 const systemInfo = wx.getSystemInfoSync(); // 胶囊按钮位置信息 const menuButtonInfo = wx.getMenuButtonBoundingClientRect(); // 导航栏高度 = 状态栏高度 + 44 this.globalData.navBarHeight = systemInfo.statusBarHeight + 44; this.globalData.menuRight = systemInfo.screenWidth - menuButtonInfo.right; this.globalData.menuTop = menuButtonInfo.top; this.globalData.menuHeight = menuButtonInfo.height; /** 获取设备类型 */ let res = wx.getSystemInfoSync(); if (res.platform == "ios") { this.globalData.deviceType = "ios"; } if (res.platform == "android") { this.globalData.deviceType = "android"; } }, globalData: { navBarHeight: 0, // 导航栏高度 menuRight: 0, // 胶囊距右方间距(方保持左、右间距一致) menuTop: 0, // 胶囊距底部间距(保持底部间距一致) menuHeight: 0, // 胶囊高度(自定义内容可与胶囊高度保证一致) deviceType: "ios", // 设备类型, },})
3. 创建组件文件夹 components/navigationBar
a. index.js
在index.js 中通过小程序提供的getApp()方法,获取app.js 中配置的globalData中属性
const app = getApp(); // 获取app.js 全局配置
Component({ properties: { /** 是否显示阴影 */ isBoxShadow: { type: Boolean, value: false, }, /** 回退步数 */ back: { type: Number, value: 1, }, }, data: { navBarHeight: app.globalData.navBarHeight, menuRight: app.globalData.menuRight, menuTop: app.globalData.menuTop, menuHeight: app.globalData.menuHeight, // 返回图标 backIcon:'' }, attached: function () { }, methods: { back() { wx.navigateBack({ delta: this.data.back, }); }, },});
b. index.wxml
<!-- 自定义顶部栏 --><view class="nav-bar" style="height:{{navBarHeight}}px;{{isBoxShadow?'box-shadow: 0rpx 0rpx 8rpx 0rpx rgba(0,0,0,0.1);':''}}"> <view class="nav-area" style="height:{{menuHeight}}px; min-height:{{menuHeight}}px; line-height:{{menuHeight}}px; left:{{menuRight}}px; top:{{menuTop}}px;"> <image class="nav-back" src="{{backIcon}}" bindtap="back"/> <!-- 标题 -->
<slot></slot> </view></view><!-- 占位,高度与顶部栏一样 --><view style="height:{{navBarHeight}}px;"></view>
注意: 示例的标题由于样式不确定,所有是通过调用组件时传入的。如果标题样式固定,可以通过参数直接展示标题名字,把 slot 替换成自己想要的样式 view
c. index.wxss
.nav-bar { position: fixed; width: 100%; top: 0; z-index: 9999; color: #fff; background: #fff;}
.nav-area { position: relative; display: flex; flex-direction: row; align-items: center; width: 100%; position: absolute;}
.nav-back { height: 62rpx; width: 62rpx; margin-left: 10px;}
4. 组件使用
a. 在index.json中引用组件
{ "navigationStyle": "custom", "usingComponents": { "navigation-bar": "../components/navigationBar/index" }}
b. 使用
<!-- 自定义导航 --><navigation-bar>
// 这里由于项目需求时自定义图片,实际开发中不需要 只需要通过参数传递标题名字就行 <image class="navigation-title" style="width: 144rpx;height: 46rpx;" src={{img}} /></navigation-bar>