2024年8月2日
使用自定义导航栏的uni-app项目在真机演示时,可能会出现页面内容被手机的刘海或者状态栏给遮挡了,或者在小程序上给胶囊按钮给档住了。这时候就需要获取刘海屏状态了和胶囊按钮的高度来获取安全渲染区域.

1. CSS内置变量

来自uni-aap官网:https://uniapp.dcloud.net.cn/tutorial/syntax-css.html#css-变量

–status-bar-height: 系统状态栏高度
–window-top: 内容区域距离顶部的距离
–window-bottom: 内容区域距离底部的距离

  • 不同平台适配不一致,详细查阅参考地址

具体用例

避开刘海屏

//状态栏占位组件样式
.status_bar{
    height:var(--status-bar-height);
}

避开NavigationBar和TabBar的安全区域

//安全区域组件样式
.safeArea{
    margin-top:var(--window-top);
    margin-bottom:var(--window-bottom);
}

2. uni.getWindowInfo()

https://uniapp.dcloud.net.cn/api/system/getWindowInfo.html#getwindowinfo-harmonyos-next-兼容性

获取窗口信息,基于本文我们需要的窗口信息为safeAreaInsets(安全区域与屏幕边的插入值)和safeArea(安全区域)
safeAreaInsets的属性有:

  • left 安全区域左侧插入位置
  • right 安全区域右侧插入位置
  • top 安全区顶部插入位置
  • bottom 安全区域底部插入位置
    safeArea的属性有:
  • width 安全区域的宽度,单位逻辑像素
  • height 安全区域的高度,单位逻辑像素

具体用例

获取一个去除状态栏、底部滑动条的渲染区域

<template>
    <view class='safeArea'></view>
</template>

<script>
    uni
     .createSelectorQuery()
     .select('.safeArea')
     .fields({ computedStyle: [ 'height','marginTop','marginBottom'] }, (data) => {
        //获取安全区域
        data.hetght=`${uni.getWindowInfo().safeArea.height}`
        //获取安全区域距离屏幕边的距离
        data.marginTop=`${uni.getWindowInfo().safeAreaInsets.top}`
        data.marginBottom=`${uni.getWindowInfo().safeAreaInsets.bottom}`
     })
     .exec()
</script>
Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐