uniapp小程序头部状态处理
js:
const SYSTEM_INFO = uni.getSystemInfoSync();
const statusBarHeight = ref(SYSTEM_INFO.statusBarHeight|| 0 )
const titleBarHeight = ref(0);
let {top,height} = uni.getMenuButtonBoundingClientRect();
titleBarHeight.value = (height + (top - statusBarHeight.value) * 2)
titleBarHeight.value = 60
在视图上使用:style进行高度处理:
<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">{{title}}</view>
<view class="search">
<uni-icons type="search" color="#8888" size="18"></uni-icons>
<text>搜索</text>
</view>
</view>
</view>
<!-- 设置高度 应对下方部分内容被遮盖 -->
<view class="fill" :style="{height:(statusBarHeight + titleBarHeight) + 'px'}"></view>
</view>
</template>
将处理步骤进行封装
封装的js文件
const SYSTEM_INFO = uni.getSystemInfoSync();
export const getStatusBarHeight = () => SYSTEM_INFO.statusBarHeight|| 0 ;
export const getTitleBarHeight = () => {
if(uni.getMenuButtonBoundingClientRect){
let {top,height} = uni.getMenuButtonBoundingClientRect();
return height + (top - getStatusBarHeight()) * 2;
}else{
return 60;
}
}
export const getNavBarWidth = () => {
let width = SYSTEM_INFO.windowWidth || 375;
if(uni.getMenuButtonBoundingClientRect()){
let {left} = uni.getMenuButtonBoundingClientRect();
return left ;
}else{
return 375;
}
return width;
}
export const getNavBarHeight = () => getStatusBarHeight() + getTitleBarHeight();
在页面中的使用
<template>
<view class="layout">
<view class="navbar">
<!-- 小程序头部空格空间 -->
<view class="statusBar" :style="{height:getStatusBarHeight()+ 'px'} "></view>
<!-- 头部主要部分 名称与搜索 -->
<view class="titleBar" :style="{height:getTitleBarHeight()+ 'px'}">
<view class="title">{{title}}</view>
<view class="search">
<uni-icons type="search" color="#8888" size="18"></uni-icons>
<text>搜索</text>
</view>
</view>
</view>
<!-- 设置高度 应对下方部分内容被遮盖 -->
<view class="fill" :style="{height:getNavBarHeight()+ 'px'}"></view>
</view>
</template>
<script setup>
import {getNavBarHeight,getStatusBarHeight,getTitleBarHeight} from '@/utils/babel-header.js'
</script>
在vue2中使用需要将方法先在页面中进行调用,例如created||mounted||computer中调用
<template>
<view class="layout">
<view class="navbar">
<view class="statusBar" :style="{height:StatusBarHeight + 'px'}"></view>
<view class="titleBar">
<view class="content">
title {{StatusBarHeight}}
</view>
<view class="menuButton"></view>
</view>
</view>
</view>
</template>
<script>
import {getStatusBarHeight} from "@/utils/babel-header.js"
export default {
name:"index-header",
data() {
return {
StatusBarHeight:0,
};
},
created(){
this.StatusBarHeight = getStatusBarHeight()
console.log(this.StatusBarHeight);
}
}
</script>