uni-app项目实战笔记17--获取系统信息getSystemInfo状态栏和胶囊按钮
接着上一篇笔记,在添加头部导航栏后,H5显示正常:
但在微信小程序中,由于刘海屏的存在,添加的头部导航栏跟状态栏重叠在一起:
因此需要获取状态栏的高度以便状态栏和导航栏错开不重叠在一起。同时头部导航栏通过与右侧的胶囊按钮在同一水平线上,因此也需要获取胶囊按钮的高度来控制显示。
uniapp提供了获取系统信息的API:getSystemInfo(异步操作),详情可访问uniapp官方文档:系统信息的概念 | uni-app官网。
下面我们通过代码,实现在微信小程序中将头部导航栏与刘海屏,状态栏拉开距离。
<template><view class="layout"><view class="navBar"><view class="statusBar" :style="{height:statusBarHeight+'px'}"></view><view class="titleBar" :style="{height:titleBarHeight+'px'}"><view class="title">标题</view><view class="search"><uni-icons class="icon" type="search" color="#888" size="18"></uni-icons><text class="text">搜索</text></view></view></view><view class="fill" :style="{height:statusBarHeight+titleBarHeight+'px'}"></view></view>
</template><script setup>import {ref} from 'vue'//使用同步获取系统信息let system = uni.getSystemInfoSync();//从系统信息中获取状态栏高度let statusBarHeight= ref(system.statusBarHeight)//获取胶囊按钮信息let MENU_BUTTON = uni.getMenuButtonBoundingClientRect()//获取胶囊按钮的高度和距离顶部的距离let {top,height} =uni.getMenuButtonBoundingClientRect()//获取状态栏高度let titleBarHeight = ref(height+(top-statusBarHeight.value)*2)console.log(titleBarHeight)console.log(top,height)
</script>
知识要点:
动态适配状态栏高度
通过
uni.getSystemInfoSync()
获取设备系统信息,提取statusBarHeight
(状态栏高度,通常包含时间、电池栏等)。状态栏高度通过
:style
动态绑定到顶部占位视图(避免内容被状态栏遮挡)。动态计算标题栏高度
通过
uni.getMenuButtonBoundingClientRect()
获取小程序胶囊按钮的位置信息(如微信小程序右上角的菜单按钮)。根据胶囊按钮的
top
(距离顶部距离)和height
(高度),结合状态栏高度,计算出标题栏的实际高度titleBarHeight
。
公式:
标题栏高度 = 胶囊按钮高度 + (胶囊按钮top - 状态栏高度) * 2
(目的是让标题栏高度包含胶囊按钮的上下边距,保持视觉居中)
top - statusBarHeight
:胶囊按钮顶部到状态栏底部的距离,乘以 2 表示上下对称留白(保证标题文字垂直居中)。完整的导航栏结构
状态栏占位:透明区域,高度为
statusBarHeight
。标题栏内容:
左侧显示固定标题“标题”。
右侧显示搜索图标和文字(通过
uni-icons
组件实现)。底部填充块:用
fill
视图填充导航栏占用的空间,防止页面内容被导航栏覆盖。
最终效果: