2022-07-05 uni获取状态栏高度
// 获取状态栏的高度 let menuButtonObject = uni.getMenuButtonBoundingClientRect(); //获取菜单按钮(右上角胶囊按钮)的布局位置信息。坐标信息以屏幕左上角为原点。 uni.getSystemInfo({ //获取系统信息 success: res => { let navHeight = menuButtonObject.height + (menuButtonObject.top - res.statusBarHeight) * 2; //状态栏高度=菜单按钮高度+(菜单按钮与顶部距离-状态栏高度)*2 this.titleBarHeight = (Number(navHeight) + 4) / 0.425; this.statusBarHeight = (Number(res.statusBarHeight) + 4) / 0.425; let a = res.statusBarHeight; }, fail(err) { console.log(err); } });
转载于https://www.jianshu.com/p/1eb20247ef22,略有改动。
=================== 2023-06-19 =====================
注:该方案适用于小程序端,不适用于app和h5端,因为uni.getMenuButtonBoundingClientRect()方法只适用于小程序端。
那么,app端该如何获取状态栏高度呢?解决方案如下:
mounted() { const query = uni.createSelectorQuery().in(this); query.select('#main').boundingClientRect(data => { // console.log("得到布局位置信息" + JSON.stringify(data)); // console.log("节点离页面顶部的距离为" + data.top); this.height2 = data.top }).exec(); },
通过获取节点的位置信息来拿到该节点距离顶部的高度从而拿到状态栏高度,上面的方法要放在mounted里,接着在页面中绑定一个节点即可,如:
<template> <div> <view id="main" :style="'top: ' + height2 + ' px'"></view> </div> </template>
注:该方案来自http://t.csdn.cn/A9jCO
最后:如果是h5端,可以查看uniapp官网提供的方案:https://uniapp.dcloud.net.cn/tutorial/syntax-css.html#css-%E5%8F%98%E9%87%8F,这个方案是通过一个css变量【--status-bar-height】来实现的。
不过,,嗯,,,看官网写的吧:
- 由于在 H5 端,不存在原生导航栏和 tabbar,也是前端 div 模拟。如果设置了一个固定位置的居底 view,在小程序和 App 端是在 tabbar 上方,但在 H5 端会与 tabbar 重叠。此时可使用
--window-bottom
,不管在哪个端,都是固定在 tabbar 上方。
=================== 2023-07-03 =====================