微信小程序自定义导航栏(适配刘海屏)
1.首先在根据官方文档,我们在小程序修改 app.json 中的 window 的属性 "navigationStyle": "custom"。
{ "pages":[ "pages/index/index", ], "window":{ "navigationBarBackgroundColor": "#fff", "navigationBarTextStyle":"black", "navigationStyle": "custom" } }
//app.js App({ onLaunch: function() { wx.getSystemInfo({ success: e => { this.globalData.statusBar = e.statusBarHeight; //状态栏高度 let custom = wx.getMenuButtonBoundingClientRect();//菜单按钮 this.globalData.custom = custom; this.globalData.customBar = custom.bottom + custom.top - e.statusBarHeight; //计算得到定义的状态栏高度 } }) }, globalData: {} }) //以iPhoneX为例 拿到的数据为 (获取到的数据单位统一为px) // globalData: { // custom: { // bottom: 82 // height: 32 // left: 278 // right: 365 // top: 50 // width: 87 // } // customBar: 88 // statusBar: 44 // }
3.自定义栏的配置和需要拿到的相关数据都拿到了,接下来就去写导航栏的样式。( 注:自定义导航栏不存在原生的返回按钮,所以返回按钮需要我们自己写出来并添加返回事件)
样式问题通过css实现的方式有很多,这里附上简单的代码
wxml:
<view class=nav style="height:{ {customBar}}px"> <view class=con style="height:{ {customBar}}px;padding-top:{ {statusBar}}px;"> <view class="backBtn" bindtap="goBack" > <text class="iconfont icon-fanhui"></text> </view> <view class="title" style="top:{ {statusBar}}px">首页</view> </view> </view>
wxss:
view, scroll-view, swiper, button, input, textarea, label, navigator, image { box-sizing: border-box; } .nav { min-height: 0px; background: rgb(38, 185, 243); color: #fff; z-index: 9999; position: relative; } .con { position: fixed; width: 100%; top: 0; display: flex; } .title { position: absolute; text-align: center; width: calc(100% - 340rpx); left: 0; right: 0; bottom: 0; top: 0; margin: auto; height: 60rpx; font-size: 32rpx; line-height: 60rpx; pointer-events: none; text-overflow: ellipsis; white-space: nowrap; overflow: hidden; } .backBtn { margin-left: 30rpx; font-size: 36rpx; display: flex; align-items: center; height: 100%; justify-content: center; max-width: 100%; }
js:
const app = getApp(); Page({ data: { statusBar: app.globalData.statusBar, customBar: app.globalData.customBar, custom: app.globalData.custom }, goBack(){ wx.navigateBack({ delta: 1 }); } })
上一篇:
uniapp开发微信小程序-2.页面制作
下一篇:
uni-app实现选项卡功能