微信小程序自定义导航栏兼容适配所有机型
目前小程序已在前端占了一席之地,最近公司项目上用的就是小程序开发,由于功能及页面不是很多,所以直接原生开发,毕竟坑可能会少点,在开发过程中,小程序自带导航栏和客户的设计稿导航栏排在一起,感觉很别扭,因此要求去掉微信的自带导航栏,微信提供了这方面的api,接下来我们就实操。
这是小程序官方文档截图,可以看到导航栏样式支持两种,默认是带导航栏,另外一种是自定义导航栏-custom,如果使用自定义导航栏,我们可以
全局配置
//app.json"window": {
"navigationStyle": "custom"}
单页面配置
//page.json{
"navigationStyle": "custom"}
效果对比
1.获取导航栏高度及按钮位置
微信提供了获取导航栏高度的Api和胶囊按钮位置的Api
// 系统信息constsystemInfo = wx.getSystemInfoSync();
// 胶囊按钮位置信息constmenuButtonInfo = wx.getMenuButtonBoundingClientRect();
在控制台打印出这两个Api返回结果
这里面我们只说几个我们接下来用到的参数。
statusBarHeight // 状态栏高度screenWidth // 胶囊的宽度top // 胶囊到顶部距离height // 胶囊的高度right // 胶囊距离右边的距离通过这几个参数,我们可以计算出状态栏的高度,微信胶囊所占的高度(存在padding值,可以使元素和胶囊纵向居中)
首先在app.js中定义全局data-globalData
globalData: {
navBarHeight: 0, // 导航栏高度 menuBotton: 0, // 胶囊距底部间距(保持底部间距一致) menuRight: 0, // 胶囊距右方间距(方保持左、右间距一致) menuHeight: 0, // 胶囊高度(自定义内容可与胶囊高度保证一致)},
新建个方法
setNavBarInfo() {
// 获取系统信息const systemInfo = wx.getSystemInfoSync();
// 胶囊按钮位置信息const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
// 导航栏高度 = 状态栏到胶囊的间距(胶囊距上距离-状态栏高度) * 2 + 胶囊高度 + 状态栏高度 this.globalData.navBarHeight = (menuButtonInfo.top - systemInfo.statusBarHeight) * 2+ menuButtonInfo.height + systemInfo.statusBarHeight;
this.globalData.menuBotton = menuButtonInfo.top - systemInfo.statusBarHeight;
this.globalData.menuRight = systemInfo.screenWidth - menuButtonInfo.right;
this.globalData.menuHeight = menuButtonInfo.right;
}
在onLaunch中调用,因为我这个项目是所有的导航都不用微信自带的,所以在app.js
中调用及设置data。
onLaunch() {
this.setNavBarInfo()
},
到这里所需要用到的都已经存了起来,页面用法也比较简单,排除状态栏的高度,设置导航栏的高度和胶囊高度保持,用flex布局。
2.页面适配
首先page.js中定义变量
varapp = getApp()
Page({
/**
* 页面的初始数据
*/data: {
navBarHeight: app.globalData.navBarHeight, //导航栏高度 menuBotton: app.globalData.menuBotton, //导航栏距离顶部距离 menuRight: app.globalData.menuRight, //导航栏距离右侧距离 menuHeight: app.globalData.menuHeight, //导航栏高度}
})
页面使用
<view class="nav" style="height:{{navBarHeight}}px;"> <view class="nav-main"> <!-- 胶囊区域 --> <view class="capsule-box" style="style="height:{{menuHeight+menuBotton*2}}px; min-height:{{menuHeight}}px; line-height:{{menuHeight}}px; bottom:0px;padding:0 {{menuRight}}px;"> <!-- 导航内容区域 --> <slot></slot> </view> </view></view>wxss
/* 公共导航 */.nav{
position: fixed;
top: 0;
left: 0;
box-sizing: border-box;
width: 100vw;
z-index: 1000;
}
.nav-main{
width: 100%;
height: 100%;
box-sizing: border-box;
position: relative;
}
.nav .capsule-box{
position: absolute;
box-sizing: border-box;
width: 100%;
display: flex;
align-items: center;
}
最终效果
此种适配方案适应所有手机,应该说是最优的选择。
以上就是关于《微信小程序自定义导航栏兼容适配所有机型》的全部内容,本文网址:https://www.7ca.cn/baike/22183.shtml,如对您有帮助可以分享给好友,谢谢。