实现的前提
首先查看文档,看文档里关于自定义导航栏是怎么规定的,有哪些限制;还有小程序自定义导航栏全局配置和单页面配置的微信版本和调试库的最低支持版本。
在app.json window 增加 navigationStyle:custom ,顶部导航栏就会消失,只保留右上角胶囊状的按钮,如何修改胶囊的颜色呢;胶囊体目前只支持黑色和白色两种颜色,在app.josn window 加上 "navigationBarTextStyle":"white/black"。
实现的步骤
自定义导航栏文本,是否显示返回,是否显示返回首页,导航栏高度;
statusBarHeight,用来获取手机状态栏的高度,调用wx.getSystemInfo获取,navigationBarHeight+默认的高度,这个是设定整个导航栏的高度;
还有注意的,在写样式距离和大小时建议都用px,因小程序右边的胶囊也是用的px,不是rpx;
因为自定义导航栏每个页面都要写,所以把导航栏封装了公共组件,这样只需要在每个页面引入即可。
效果图
组件结构navbar.wxml
这里有个需注意的问题,就是一般会出现自定义导航栏,下拉页面,导航栏也随着会下拉,这种问题是因为设置fixed后页面元素整体上移了navigationBarHeight,所以在此组件里设置一个空白view元素占用最上面的navigationBarHeight这块高度
组件样式navbar.wxss
.custom{
position: fixed;
width: 100%;
top: 0;
left: 0;
height: 45px;
background: #1d8be8;
z-index: 999;
}
.title-container {
height: 44px;
display: flex;
align-items: center;
position: relative;
}
.capsule {
margin-left: 10px;
height: 32px;
border-radius: 16px;
display: flex;
align-items: center;
}
.capsule > view {
width: 32px;
height: 60%;
position: relative;
}
.capsule image {
width: 60%;
height: 100%;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
.title {
color: white;
position: absolute;
left: 104px;
right: 104px;
font-size: 14px;
text-align: center;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
@font-face {font-family: "iconfont";
src: url('data:application/x-font-woff2;charset=utf-8;base64, format('woff2');
}
.iconfont {
font-family: "iconfont" !important;
font-style: normal;
color: #fff;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.icon-home:before { content: "\e60c"; }
.icon-back:before { content: "\e618"; }
设置组件参数navbar.json
{
"component": true,
"usingComponents": {}
}
组件navbar.js
Component({
properties: {
navigationBarTitle: {
type: String,
value: ''
},
back: {
type: Boolean,
value: false
},
home: {
type: Boolean,
value: false
},
bg: {
type: String,
value: ''
}
},
data: {
statusBarHeight: wx.getSystemInfoSync()['statusBarHeight']
},
methods: {
backHome: function () {
wx.reLaunch({
url: '/pages/study/study',
})
},
back: function () {
wx.navigateBack({
delta: 1
})
}
}
})
调用组件的页面.json
{
"usingComponents": {
"navBar": "/component/navbar/navbar"
},
"navigationStyle": "custom"
}