整理一下微信小程序自定義導航欄和劉海屏適配問題
1.首先在根據官方文檔,我們在小程序修改 app.json 中的 window 的屬性 "navigationStyle": "custom"
{
"pages":[
"pages/index/index",
],
"window":{
"navigationBarBackgroundColor": "#fff",
"navigationBarTextStyle":"black",
"navigationStyle": "custom"
}
}
2..通過微信小程序API,wx.getSystemInfo獲取設備狀態欄高度,wx.getMenuButtonBoundingClientRect()獲取菜單按鈕(右上角膠囊按鈕)的布局位置信息。坐標信息以屏幕左上角為原點
//app.js
App({
onLaunch: function() {
wx.getSystemInfo({
success: e => {
this.globalData.statusBar = e.statusBarHeight; //狀態欄高度
let custom = wx.getMenuButtonBoundingClientRect();//菜單按鈕
this.globalData.custom = custom;
this.globalData.customBar = custom.bottom + custom.top - e.statusBarHeight;
//計算得到定義的狀態欄高度
}
})
},
globalData: {}
})
//以iPhoneX為例 拿到的數據為 (獲取到的數據單位統一為px)
// globalData: {
// custom: {
// bottom: 82
// height: 32
// left: 278
// right: 365
// top: 50
// width: 87
// }
// customBar: 88
// statusBar: 44
// }
3.自定義欄的配置和需要拿到的相關數據都拿到了,接下來就去寫導航欄的樣式。( 注:自定義導航欄不存在原生的返回按鈕,所以返回按鈕需要我們自己寫出來並添加返回事件)
樣式問題通過css實現的方式有很多,這里附上簡單的代碼
wxml:
<view class='nav' style="height:{{customBar}}px">
<view class='con' style="height:{{customBar}}px;padding-top:{{statusBar}}px;">
<view class="backBtn" bindtap="goBack" >
<text class="iconfont icon-fanhui"></text>
</view>
<view class="title" style="top:{{statusBar}}px">首頁</view>
</view>
</view>
wxss:
view, scroll-view, swiper, button, input, textarea, label, navigator, image {
box-sizing: border-box;
}
.nav {
min-height: 0px;
background: rgb(38, 185, 243);
color: #fff;
z-index: 9999;
position: relative;
}
.con {
position: fixed;
width: 100%;
top: 0;
display: flex;
}
.title {
position: absolute;
text-align: center;
width: calc(100% - 340rpx);
left: 0;
right: 0;
bottom: 0;
top: 0;
margin: auto;
height: 60rpx;
font-size: 32rpx;
line-height: 60rpx;
pointer-events: none;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
}
.backBtn {
margin-left: 30rpx;
font-size: 36rpx;
display: flex;
align-items: center;
height: 100%;
justify-content: center;
max-width: 100%;
}
js:
const app = getApp();
Page({
data: {
statusBar: app.globalData.statusBar,
customBar: app.globalData.customBar,
custom: app.globalData.custom
},
goBack(){
wx.navigateBack({
delta: 1
});
}
})