❗❗❗此计算方法仅适用于navigationStyle设置为custom时 模拟器上显示的效果可能和真机不同,以真机为准 以下API获取的数值的单位都是像素(px),并非rpx
页面划分
- 状态栏(statusBar)
- 不同设备的状态栏的高度是不同改的
- 导航栏(navBar)
- 导航栏高度 = 胶囊高度 + 胶囊的上下边距
- 胶囊的上下边距相等
- 通过wx.getMenuButtonBoundingClientRect()可以获取胶囊的宽高等信息
- 安全区域(safeArea)
- 指的是内容区域 + 导航栏
- 通过wx.getWindowInfo()获取安全区域的宽高等信息
获得各区域的高度
- 状态栏(statusBar)
const statusBarHeight = wx.getWindowInfo().statusBarHeight;
- 导航栏(navBar)
- 首先计算胶囊上边距,乘2,加上胶囊高度就是导航栏高度
const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
/*
{
width: 87, 胶囊的宽度
height: 32, 胶囊的高度
top: 48, 胶囊左上角到状态栏顶边的垂直距离(E点到AB边的垂直距离)
bottom: 80, 胶囊左下角到状态栏顶边的垂直距离(G点到AB边的垂直距离)
left: 281,
right: 368,
}
*/
- 胶囊的上边距等于menuButtonInfo.top - statusBarHeight
- 所以导航栏的高度等于const navBarHeight = menuButtonInfo.height + (menuButtonInfo.top - statusBarHeight) * 2
- 安全区域(safeArea)和内容区
- 安全区域包含了导航栏,所以安全区域高度 - 导航栏高度就是内容区的高度
const { safeArea } = wx.getWindowInfo();
/*
{
width: 375,
height: 734,
top: 44,
bottom: 778,
left: 0,
right: 375
}
*/
const safeAreaHeight = safeArea.height; // 安全区域高度
const contentHeight = safeAreaHeight - navBarHeight;
完整代码
- 效果图
- index.json
{
"usingComponents": {},
"navigationStyle": "custom"
}
1 2 3 4
- index.wxml
<view class="status-bar" style="height: {{statusBarHeight}}px;"></view>
<view class="nav-bar" style="height: {{navBarHeight}}px;"></view>
<!-- <view class="safe" style="height: {{safeHeight}}px;"></view> -->
<view class="content" style="height: {{safeHeight - navBarHeight}}px"></view>
<view class="bottom-safe" style="height: {{bottomSafeHeight}}px;"></view>
- index.wxss
page {
background-color: red;
}
view {
width: 100%;
}
.status-bar {
background-color: rgb(55, 150, 187);
}
.nav-bar {
background-color: bisque;
}
.safe {
background-color: burlywood;
}
.content {
background-color: rgb(243, 86, 222);
}
.bottom-safe {
background-color: rgb(59, 112, 209);
}
- index.js
Page({
data: {
statusBarHeight: 0,
navBarHeight: 0,
safeHeight: 0,
bottomSafeHeight: 0,
},
onLoad() {
// 获取的数值单位是px
const windowInfo = wx.getWindowInfo();
const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
console.log(windowInfo);
console.log(menuButtonInfo);
let statusBarHeight = windowInfo.statusBarHeight;
let navBarHeight =
menuButtonInfo.height + (menuButtonInfo.top - statusBarHeight) * 2;
let safeHeight = windowInfo.safeArea.height;
let bottomSafeHeight =
windowInfo.screenHeight - windowInfo.safeArea.height - statusBarHeight;
this.setData({
statusBarHeight,
navBarHeight,
safeHeight,
bottomSafeHeight,
});
console.log("statusBarHeight", statusBarHeight);
console.log("navBarHeight", navBarHeight);
console.log("safeHeight", safeHeight);
console.log("bottomSafeHeight", bottomSafeHeight);
},
});