在app.js中进行计算,之后放入全局,封装component,放入全局组件直接使用
计算公式:statusBarHeight + height + (top - statusBarHeight) * 2
onlunch() {
// 获取状态栏高度
const { statusBarHeight } = wx.getSystemInfoSync();
// 得到右上角菜单的位置尺寸
const menuButtonObject = wx.getMenuButtonBoundingClientRect();
const { top, height } = menuButtonObject;
// 计算导航栏的高度
// 此高度基于右上角菜单在导航栏位置垂直居中计算得到
const navBarHeight = height + (top - statusBarHeight) * 2;
// 计算状态栏与导航栏的总高度
const statusNavBarHeight = statusBarHeight + navBarHeight;
this.globalData.statusNavBarHeight = statusNavBarHeight;
this.globalData.navBarHeight = navBarHeight;
this.globalData.statusBarHeight = statusBarHeight;
},
globalData: {
statusNavBarHeight: 0,
navBarHeight: 0,
statusBarHeight: 0,
}
封装组件
<view class="nav" style="height:{{statusNavBarHeight}}px;">
<view class="nav_con" style="height:{{navBarHeight}}px;top: {{statusBarHeight}}px;">
<view class="left_con">
<image src="./back.png" bindtap="backTrigger" class="back" wx:if="{{back}}" />
<slot name="left">
</slot>
</view>
<view class="nav_title">
{{title}}
</view>
<view class="right_con">
<slot name="right"></slot>
</view>
</view>
</view>
/* components/navbar/navbar.wxss */
.nav {
width: 100%;
background-color: #fff;
position: sticky;
z-index: 9;
top: 0;
padding: 0 30rpx;
box-sizing: border-box;
}
.left_con,
.right_con,
.nav_title {
vertical-align: middle;
height: 100%;
display: flex;
align-items: center;
}
.left_con .back {
width: 30rpx;
height: 30rpx;
vertical-align: middle;
}
.nav_con {
position: relative;
width: 100%;
display: grid;
grid-template-columns: 1fr 2fr 1fr;
align-items: center;
}
.nav_title {
text-align: center;
justify-content: center;
font-weight: 500;
font-size: 36rpx;
color: #000000;
letter-spacing: 0;
overflow: hidden;
}
const app = getApp();
Component({
options: {
multipleSlots: true,
},
properties: {
title: {
type: String,
optionalTypes: [Number, null],
},
back: {
type: Boolean,
value: false,
},
},
lifetimes: {
attached() {
let {
statusNavBarHeight,
navBarHeight,
statusBarHeight,
} = app.globalData;
this.setData({
statusNavBarHeight,
navBarHeight,
statusBarHeight,
});
},
},
/**
* 组件的初始数据
*/
data: {
statusNavBarHeight: 0,
navBarHeight: 0,
statusBarHeight: 0,
},
/**
* 组件的方法列表
*/
methods: {
backTrigger() {
let that = this;
wx.navigateBack({
delta: 1,
fail() {
that.triggerEvnet("back");
},
});
},
},
});