app上下安全区域
更新时间: 2025-09-19 10:21:35
做APP有个绕不开的问题就是机型适配,不同的机型上面和下面工具栏的高度都是不一样的,因此写APP的时候需要注意顶部和底部的安全距离
# 动态获取状态栏高度
适配不同设备(如刘海屏、水滴屏)的顶部状态栏
// 同步获取系统信息
const SYSTEM_INFO = uni.getSystemInfoSync();
// 获取状态栏高度
export const getStatusBarHeight = ()=>SYSTEM_INFO.statusBarHeight || 0
1
2
3
4
2
3
4
- uni.getSystemInfoSync()返回设备完整信息,包括屏幕尺寸、操作系统等。
- statusBarHeight:状态栏高度(顶部显示时间、电量的区域),单位px
# 精确计算标题栏高度
有的机型或平台会有右上角的胶囊按钮
// 获取标题栏高度
export const getTitleBarHeight = () => {
// 检查平台是否支持胶囊按钮API
if(uni.getMenuButtonBoundingClientRect) {
let {top, height} = uni.getMenuButtonBoundingClientRect()
// 核心公式:(胶囊顶部距离-状态栏高度)*2 + 胶囊高度
return (top - getStatusBarHeight()) * 2 + height
}else{
return 40
}
}
// 获取状态栏+标题栏高度
export const getNavBarHeight = () => getStatusBarHeight() +getTitleBarHeight()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
关键公式推导:
- 胶囊按钮到状态栏底部的距离 = top - statusBarHeight
- 上下间距总和 = 2 * (top - statusBarHeight)
- 标题栏高度 = 上下间距 + 胶囊高度
# 底部安全区域适配
避免内容被iOS底部黑条或Android虚拟按键遮挡
.safe-area-inset-bottom {
height: env(safe-area-inset-bottom);
}
1
2
3
2
3
env()函数获取设备底部安全区域高度,避免内容被iOS底部黑条遮挡。