小程序自定义导航栏
步骤
1.在 app.json 里面把 "navigationStyle" 设置为 "custom"
这样子之后就只会保留右上角胶囊按钮了。
2.我们用wx.getMenuButtonBoundingClientRect() 获取胶囊按钮的布局位置信息,
用wx.getSystemInfoSync() 获取系统信息,里面有个参数:statusBarHeight(状态栏高度),是我们后面计算整个导航栏的高度需要用到的。
计算公式: 导航栏高度 = 状态栏到胶囊的间距(胶囊距上距离-状态栏高度) * 2 + 胶囊高度 + 状态栏高度
代码如下:
onLaunch: function(options) {
const that = this;
// 获取系统信息
const systemInfo = wx.getSystemInfoSync();
// 胶囊按钮位置信息
const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
// 导航栏高度 = 状态栏到胶囊的间距(胶囊距上距离-状态栏高度) * 2 + 胶囊高度 + 状态栏高度
that.globalData.navBarHeight = (menuButtonInfo.top - systemInfo.statusBarHeight) * 2 + menuButtonInfo.height + systemInfo.statusBarHeight;
that.globalData.menuRight = systemInfo.screenWidth - menuButtonInfo.right;
that.globalData.menuBotton = menuButtonInfo.top - systemInfo.statusBarHeight;
that.globalData.menuHeight = menuButtonInfo.height;
},
// 数据都是根据当前机型进行计算,这样的方式兼容大部分机器
globalData: {
navBarHeight: 0, // 导航栏高度
menuRight: 0, // 胶囊距右方间距(方保持左、右间距一致)
menuBotton: 0, // 胶囊距底部间距(保持底部间距一致)
menuHeight: 0, // 胶囊高度(自定义内容可与胶囊高度保证一致)
}
})
<view class="nav-bar" style="height:{{navBarHeight}}px;">
<input class="search" placeholder="输入关键词!" style="height:{{menuHeight}}px; min-height:{{menuHeight}}px; line-height:{menuHeight}}px; left:{{menuRight}}px; bottom:{{menuBotton}}px;"></input>
</view>
<!--
内容区域:
自定义顶部栏用的fixed定位,会遮盖到下面内容,注意设置好间距
-->
<view class="content" style="margin-top:{{navBarHeight}}px;"></view>