我在這裏封裝了一個類,可以直接使用
export default class NavBarInfo {
constructor() {
this.statusBarHeight = 0; //狀態欄的高度
this.navigatorHeight = 0; //導航欄高度
this.menuHeight = 0; //膠囊高度
this.menuTop = 0; //膠囊與頂部的距離
this.totalHeight = 0; //總高度
this.getNavBarInfo();
}
getNavBarInfo() {
let menu = {};
let system = {};
//獲取系統信息
uni.getSystemInfo({
success: (res) => (system = res)
});
//獲取膠囊信息
try {
menu = uni.getMenuButtonBoundingClientRect();
} catch {
menu = {
height: 0,
top: 0
};
}
//計算組件高度
this.statusBarHeight = system.statusBarHeight; //狀態欄高度
this.menuHeight = menu.height; //膠囊高度
this.menuTop = menu.top; //膠囊與頂部的距離
//導航欄高度= (膠囊頂部距離-狀態欄高度) x 2 + 膠囊的高度
// 這裏用 x 1就是底部跟膠囊底部對齊,如果 x 2則是膠囊底部還留有一個邊距的位置
this.navigatorHeight = (menu.top - system.statusBarHeight) * 1 + menu.height;
//總高度 = 狀態欄的高度 + 導航欄高度
this.totalHeight = this.statusBarHeight + this.navigatorHeight;
}
}
頁面使用
<template>
<view class="container"></view>
</template>
<script setup>
import NavBarInfo from '@/utils/NavBarInfo.js';
let navBarInfo = new NavBarInfo();
// navBarInfo.totalHeight 頂部總高度
</script>