目录
1.开始
在 页面json文件中把 "navigationStyle" 设置为 "custom"就可以自定义导航栏了
{
"usingComponents": {},
"navigationStyle":"custom"
}
2.图解
3.实现
微信AIP wx.getMenuButtonBoundingClientRect() 可以得到胶囊信息
Object wx.getMenuButtonBoundingClientRect() | 微信开放文档 (qq.com)
在这里需要用到{ width, height, top, right }
再根据微信AIP wx.getSystemInfo() 获取设备信息,得到状态栏高度
wx.getSystemInfo(Object object) | 微信开放文档 (qq.com)
通过状态栏高度和胶囊信息,可以得到胶囊距状态栏距离,内容的宽高等
接下来就是实现了
.wxml
<view class="nav" style="height: {{navHeight}}px; width: 100%; background: rgba(255, 255, 255, {{opacity}});">
<view class="navcontent" style="margin-top: {{marginTop}}px; width: {{contentWidth}}px;height: {{contentHeight}}px;">
//这里的返回按钮用的是vant的icon
<van-icon name="arrow-left" size="22" style="margin-left: {{marginRight}}px;" bind:click="onClickBack" />
<view class="navtitle" style="margin-left: {{titleMargin}}px;">标题</view>
</view>
</view>
.js
data: {
navHeight:'',//导航栏高,
menuButtonInfo:'',//胶囊信息
marginTop: '', // 上边距
marginRight:'',//右侧边距
contentHeight:'',//内容高度
contentWidth:'',//内容宽度
titleMargin:'',//标题距右侧距离
},
onLoad(options) {
this.getSystemInfo()
},
getSystemInfo(){
this.setData({
menuButtonInfo: wx.getMenuButtonBoundingClientRect()
})
const { top, width, height, right } = this.data.menuButtonInfo
wx.getSystemInfo({
success: (res) => {
const { statusBarHeight } = res //状态栏高度
const margin = top - statusBarHeight//胶囊距状态栏距离
this.setData({
navHeight: (height + statusBarHeight + (margin * 2)),
marginTop: statusBarHeight + margin, // 状态栏 + 胶囊按钮边距
contentHeight: height, // 与胶囊按钮同高
contentWidth: right - width, // 胶囊按钮右边坐标 - 胶囊按钮宽度 = 按钮左边可使用宽度
marginRight:margin,
titleMargin:(right+margin)/2-60
})
},
})
},
// 点击返回
onClickBack() {
wx.navigateBack({
delta: 1
})
},
.wxss
.nav {
padding: 0rpx;
position: fixed;
top: 0;
z-index: 900;
}
.navcontent {
display: flex;
align-items: center;
}
.navtitle {
width: 60px;
text-align: center;
font-size:28rpx;
font-weight: 500;
}
参考链接