uni-app 封装刘海状态栏(适用小程序, h5, 头条小程序)
一. 创建一个hooks
hooks—>useSystemBar.js
二. useSystemBar.js
其中// #ifdef MP-WEIXIN 不是注释 这是uni-app的写法
import {ref} from 'vue';export default function() {// 获取系统信息let systemInfo = '';// #ifdef MP-WEIXINsystemInfo = uni.getWindowInfo(); // #endif// #ifndef MP-WEIXINsystemInfo = uni.getSystemInfoSync();// #endif// 获取刘海-状态栏高度let StatusBarHeight = systemInfo.statusBarHeight || 15;// 获取title-自定义内容高度let TitleBarHeight = '';if(uni.getMenuButtonBoundingClientRect){let {top,height} = uni.getMenuButtonBoundingClientRect();TitleBarHeight = height + (top - StatusBarHeight)*2 }else{TitleBarHeight = 40;}// 占位高度-胶囊离下面内容高度let NavBarHeight = StatusBarHeight + TitleBarHeight;// 判断是否是头条let ttLeftIconLeft = ''; // 头条胶囊左侧有一个固定的图标,所以要获取图标加图标左侧间距的距离// #ifdef MP-TOUTIAOlet {leftIcon:{left,width}} = tt.getCustomButtonBoundingClientRect();ttLeftIconLeft = left+ parseInt(width);// #endif// #ifndef MP-TOUTIAOttLeftIconLeft = 0;// #endifreturn {StatusBarHeight,TitleBarHeight,NavBarHeight,ttLeftIconLeft}
}
三. 使用
在需要页面上使用 下面这个文件是我的项目头部封装 你可以在titleBar标签内写自己的业务逻辑, 并且你拿到StatusBarHeight, TitleBarHeight, NavBarHeight, ttLeftIconLeft这四个值, 你就可以随意操作了
<template><!-- bar --><view class="layout"><view class="navbar"><!-- 刘海位置-状态栏 --><view class="statusBar" :style="{height: StatusBarHeight + 'px'}"></view><!-- 自己内容位置 --><view class="titleBar" :style="{height:TitleBarHeight+'px',marginLeft:ttLeftIconLeft + 'px'}"><view class="title">{{ 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:NavBarHeight +'px'}"></view></view>
</template><script setup>defineProps({title: {type:String,default:"壁纸"}})// hooksimport useSystemBar from '../../hooks/useSystemBar';const { StatusBarHeight, TitleBarHeight, NavBarHeight, ttLeftIconLeft } = useSystemBar();</script><style lang="scss" scoped>
.layout{.navbar{position: fixed;top:0;left:0;width: 100%;z-index: 10;background:linear-gradient(to bottom,transparent,#fff 400rpx),linear-gradient(to right,#beecd8 20%,#F4E2D8);.statusBar{}.titleBar{display: flex; align-items: center;padding:0 30rpx;.title{font-size: 44rpx;font-weight: 700;color: $text-font-color-1;}.search{width: 220rpx;height: 60rpx;border-radius: 60rpx;background: rgba(255,255,255,0.4);margin-left:30rpx;color:#999;font-size: 28rpx;display: flex;align-items: center;.icon{margin-left:5rpx;}.text{padding-left:10rpx;}}}}.fill{}
}
</style>