自定义导航栏高度组成:状态栏(绿色部分)、导航栏(蓝色部分)
通过调用 wx.getSystemInfoSync 获取
const res = wx.getSystemInfoSync()
this.setData({
statusBarHeight:res.statusBarHeight
})
通过获取右上角胶囊的位置信息计算,navBarPadding为导航栏上下的间隙
let res = wx.getMenuButtonBoundingClientRect()
let navBarPadding = (res.top - this.data.setStatusBarHeight) * 2
this.setData({
navBarHeight: res.height + navBarPadding
})
app.js:
App({
onLaunch () {
this.setStatusBarHeight()
this.setNavBar()
},
//设置系统状态栏高度
setStatusBarHeight(){
try {
const res = wx.getSystemInfoSync()
this.globalData.statusBarHeight = res.statusBarHeight
}catch(error){
console.log(error)
}
},
//设置导航栏height
setNavBar(){
let res = wx.getMenuButtonBoundingClientRect()
let navBarPadding = (res.top - this.globalData.statusBarHeight) * 2
this.globalData.navBarHeight = res.height + navBarPadding
},
globalData: {
statusBarHeight: 20,
navBarHeight: 44
}
})
wxml:
<view class="top-bar-wrap">
<view class="top-bar-main" style="padding-top:{{statusBarHeight}}px;height:{{navBarHeight}}px">
自定义导航栏
</view>
</view>
wxss:
.top-bar-wrap{
z-index: 9999;
position: fixed;
top: 0;
left: 0;
width: 100%;
}
.top-bar-main{
width: 100%;
display: flex;
justify-content: center;
align-items: center;
color:#fff;
}
js:
const app = getApp()
Component({
data: {
statusBarHeight: app.globalData.statusBarHeight,
navBarHeight: app.globalData.navBarHeight
}
})
setStatusBarHeight、setNavBar这两个方法最好写到app.js中,获取好放在app.globalData中,这两个高度可能不止自定义导航栏需要用到。
比如使用了自定义导航栏的页面,因为自定义导航栏是fixed定位脱离文档流,导致整个页面就会上移,所以要给页面加上padding-top,高度跟自定义导航栏的高度一致,即 statusBarHeight + navBarHeight。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有