首先修改 app.json文件中的 windows字段如下:
{
"pages": [
"pages/index/index"
],
"window": {
"navigationStyle": "custom"
}
}
为了避免遮挡用户手机顶部状态栏,还需要获取用户手机状态栏的高度,并在在每个页面中添加一个占位用的 view标签来防止遮挡用户状态栏。
在 app.js文件添加如下代码:
App({
onLaunch: function() {
wx.getSystemInfo({
success: res=> {
this.globalData.navHeight = res.statusBarHeight;
},
})
},
globalData: {
userInfo: null,
navHeight: 0,
}
})
在每个页面中添加一个占位用的 view标签,背景色与自定义的状态栏的背景色相同。
不过自定义的状态栏背景色一般不要设置成黑色或者白色,因为大多数手机的状态栏字体颜色就是黑色和白色。
js文件、wxml文件和wxss文件如下:
//index.js
const app = getApp()
Page({
data: {
//从全局变量获取状态栏高度
navHeight: app.globalData.navHeight,
},
onLoad: function () {
},
getUserInfo: function (e) {
console.log(e)
app.globalData.userInfo = e.detail.userInfo
this.setData({
userInfo: e.detail.userInfo,
hasUserInfo: true
})
}
})
<!--index.wxml-->
<view class='palce-holder-nav' style="height: {{navHeight}}px;"></view>
/*app.wxss*/
.palce-holder-nav{
width: 100%;
background-color: red;
}
显示效果如下:
最后就可以在下面添加自定义的状态栏,自定义状态栏的高度一般刚好超过胶囊的下边, 这个高度大概是系统状态栏的2倍。
代码如下:
<!--index.wxml-->
<view class='palce-holder-nav' style="height: {{navHeight}}px;"></view>
<view class='palce-holder-nav' style="height: {{2*navHeight}}px;"></view>
显示效果如下:
使用的时候在外面再包裹一层view标签:
<!--index.wxml-->
<view class='custom-navbar'>
<view class='palce-holder-nav' style="height: {{navHeight}}px;"></view>
<view class='title' style="height: {{2*navHeight}}px;"></view>
</view>
/*app.wxss*/
.custom-navbar{
width: 100%;
background-color: red;
}
.palce-holder-nav{
width: 100%;
}
甚至还可以弄出居中标题的效果:
//index.js
const app = getApp()
Page({
data: {
navHeight: app.globalData.navHeight,
title: '这是一个居中标题'
},
onLoad: function () {
},
})
<!--index.wxml-->
<view class='custom-navbar'>
<view class='palce-holder-nav' style="height: {{navHeight}}px;"></view>
<view class='title' style="height: {{2*navHeight}}px;">
<view>{{title}}</view>
</view>
</view>
/*app.wxss*/
.custom-navbar{
width: 100%;
background-color: red;
}
.palce-holder-nav{
width: 100%;
}
.title{
width: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.title>view{
width: fit-content;
color: white;
}
效果图: