微信小程序自定义顶部导航
1. 设置顶部导航模式
微信小程序的顶部导航有两种模式可选择,在app.json
文件的window
属性中添加"navigationStyle": "custom"
模式可自定义导航栏,只保留右上角胶囊按钮;
胶囊颜色也可以通过app.json
文件的window
属性中添加"navigationBarTextStyle": "white/black"
,但仅支持黑白两种颜色);
2. 获取状态栏高度和胶囊位置信息
使用wx.getSystemInfoSync
获取系统信息,通过返回的statusBarHeight
来获取状态的高度;
使用wx.getMenuButtonBoundingClientRect()
来获取胶囊的尺寸和位置,主要获取胶囊按钮的高度和top
值;
状态栏的高度和胶囊按钮间还有距离
在app.js
的onLaunch
属性中加上下面的代码
const systemInfo = wx.getSystemInfoSync();
const custom = wx.getMenuButtonBoundingClientRect();
this.globalData.systemInfo = systemInfo;
this.globalData.custom = custom;
3. 设置顶部导航栏框的样式
高度等于胶囊按钮的高度,上外边距等于状态栏高度,上下内边距等于胶囊的top减去状态栏高度;
style="height: {{custom.height}}px;margin-top: {{tabBarHeight}}px;padding: {{custom.top-tabBarHeight}}px 0"
4. 自定义顶部导航栏信息
最后就可以自定义你顶部导航栏的样式了;