小程序項目中有時候需要根據“手機信息”和“分享膠囊按鈕”的信息,來設置頁面元素;
比如,自定義導航欄,要根據手機的狀態欄和膠囊按鈕height、top來設置自定義導航欄;
獲取方法如下:
在app.vue中獲取存入store中
<script>
export default {
methods: {
getMobileInfo() {
// 膠囊按鈕信息
const menuButtonInfo = uni.getMenuButtonBoundingClientRect();
// 手機信息
const mobileInfo = uni.getSystemInfoSync();
/* 注
* screenHeight是指手機屏的高度:對應圖中1
* windowHeight是指頁面可用高度
* 圖中導航欄是自定義的,windowHeight = screenHeight - tabbar高度:對應圖中2
* 若導航欄不是自定義的,則windowHeight = screenHeight- tabbar高度 - 導航欄高度
* 如頁面沒有tabbar, 則windowHeight = screenHeight- 導航欄高度
*/
// 按鈕與手機狀態欄之間的間隙: 對應圖中3
const menuButtonMaginTopBottom =
menuButtonInfo.top - mobileInfo.statusBarHeight;
// 按鈕的border
const border = 1;
// 包含分享按鈕的容器高度:圖中藍色區域部分
const menuButtonContainerHeight =
menuButtonInfo.height + border * 2 + menuButtonMaginTopBottom * 2;
//頁面頭的高度(包含手機狀態欄):圖中綠色區域+藍色區域部分
const pageHeaderHeight =
mobileInfo.statusBarHeight + menuButtonContainerHeight;
this.$store.commit("setMobileInfo", {
// 按鈕右側距離手機屏右側距離,圖中用於設置自定義導航欄的寬;這里注意menuButtonInfo.right是指按鈕右邊界距離手機屏左側的位置
menuButtonRight: mobileInfo.windowWidth - menuButtonInfo.right,
// 按鈕左側距離手機屏左側距離
menuButtonLeft: menuButtonInfo.left,
// 按鈕寬
menuButtonWidth: menuButtonInfo.width,
// 屏幕寬
windowWidth: mobileInfo.windowWidth,
// 高度相關
statusBarHeight: mobileInfo.statusBarHeight,
menuButtonContainerHeight,
pageHeaderHeight,
windowHeightWhennoBar: mobileInfo.screenHeight - pageHeaderHeight,
});
},
},
onLaunch: function () {
// 獲取手機信息
this.getMobileInfo();
},
};
</script>
特別注意:
由於每個頁面可用高度windowHeight值可能不同,因為跟是否含有tabbar,是否自定義導航欄有關系,
所以如果有頁面需要使用windowHeight,在頁面的onReady生命周期中單獨獲取