微信小程序--自定义navBar
android平台的微信小程序NavigationBarTItle题目居左,苹果的居中,微信官方文档没有navBar的相关设置,只能自行定义。
第一步:在page.json页面的首页路由中加入"navigationStyle": "custom",取消默认的原生导航栏
第二步:新建navBar组件
具体代码:
index.vue
"navbar custom-class" :style="{height:globalData.navHeight + 'px'}">
"navbar-action-wrap navbar-action-group row item-center" :style="{top:globalData.navTop + 'px'}" style="background-color:rgba(255,255,255,0.6)">
"navbar-action_item" @click="_navBack">返回
"navbar-action_item last" @click="_toIndex">首页
'navbar-title' :style="{top:globalData.navTop + 'px'}">
{{pageName}}
navbar.css
.navbar { width: 100%; overflow: hidden; position: relative; top: 0; left: 0; z-index: 10; flex-shrink: 0; } .navbar-title { width: 100%; box-sizing: border-box; padding-left: 115px; padding-right: 115px; height: 32px; line-height: 32px; text-align: center; position: absolute; left: 0; z-index: 10; color: #333; font-size: 16px; font-weight: bold; text-overflow: ellipsis; overflow: hidden; white-space: nowrap; } .navbar-action-wrap { display: -webkit-flex; display: flex; -webkit-box-align: center; -ms-flex-align: center; -webkit-align-items: center; align-items: center; position: absolute; left: 10px; z-index: 11; line-height: 1; padding-top: 4px; padding-bottom: 4px; } .navbar-action-group { border: 1px solid #f0f0f0; border-radius: 20px; overflow: hidden; } .navbar-action_item { width: 20rpx; height: 20rpx; padding: 3px 0; color: #333; } .navbar-action-group .navbar-action_item { border-right: 1px solid #f0f0f0; padding: 3px 14px; } .navbar-action-group .last { border-right: none; }
相关计算:
小程序可以通过 wx.getMenuButtonBoundingClientRect() 获取胶囊按钮的信息 和 wx.getSystemInfo() 获取设备信息。
通过这些信息我们可以计算出上面说的3个值:
1. 整个导航栏高度 = statausBarHeight + height + (top-statausBarHeight )*2;
2. 胶囊按钮与顶部的距离 = top;
3.胶囊按钮与右侧的距离 = windowWidth - right。
关于第1步中,为啥要乘以2的原因,请看灵魂画手般的我画的图纸:
第三步:引入组件
在建立好的首页页面引入navbar组件
"container">
"nbTitle" ref="navBarRef">