微信小程序自定义导航栏,胶囊菜单按钮高度适配问题
抽离公共方法用条件编译对微信小程序,抖音小程序适配
公共组件模块建立一个导航模块
<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">标题</view>
<view class="search">
<uni-icons class="icon" type="search" size="18" color="#888"></uni-icons>
<text class="text">搜索</text>
</view>
</view>
</view>
<view class="fill" :style="{height:getNavBarHeight()+'px',marginLeft:getLeftIconLeft()+'px'}"></view>
</view>
</template>
<script setup>
import { ref } from 'vue';
import { getStatusBarHeight,getTitleBarHeight,getNavBarHeight,getLeftIconLeft } from '@/utils/system.js';
// let SYSTEM_INFO = uni.getSystemInfoSync();
// // 状态栏高度
// let statusBarHeight = ref(SYSTEM_INFO.statusBarHeight);
// // 胶囊按钮状态 解构
// let {top,height} = uni.getMenuButtonBoundingClientRect();
// let titleBarHeight = ref( height + (top - statusBarHeight.value)-2);
// console.log(titleBarHeight);
// console.log(top,height);
</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{
// border: 1px solid red;
}
.titleBar{
display: flex;
padding: 0 30rpx;
align-items: center;
// border: 1px solid green;
.title{
font-size: 22px;
font-weight: 700;
color: $text-font-color-1;
}
.search{
width: 220rpx;
height: 50rpx;
border-radius: 60rpx;
background: rgba(255,255,255,0.4);
border: 1px solid #fff;
margin-left: 30rpx;
color: #999;
font-size: 28rpx;
.text{
// display: flex;
align-items: center;
padding-left: 10rpx;
}
.icon{
margin-left: 5rpx;
}
}
}
}
.fill{
}
}
</style>
重新在项目下建立一个 utils文件夹 ,再建立一个获取系统信息的js文件,写逻辑代码
// 获取系统信息
const SYSTEM_INFO = uni.getSystemInfoSync();
// 获取状态栏高度,若未获取到则默认为0
export const getStatusBarHeight = () => SYSTEM_INFO.statusBarHeight || 10 ;
// 获取标题栏高度
export const getTitleBarHeight = ()=>{
if(uni.getMenuButtonBoundingClientRect){
// 获取胶囊按钮的位置和尺寸信息
let {top,height} = uni.getMenuButtonBoundingClientRect();
// 计算标题栏高度
return height + (top - getStatusBarHeight())*2;
}else{
// 若无法获取胶囊按钮信息,默认标题栏高度为80
return 40;
}
};
// 获取导航栏高度,导航栏高度对于状态栏高度加上标题栏高度
export const getNavBarHeight = ()=> getStatusBarHeight()+getTitleBarHeight();
// 抖音小程序
export const getLeftIconLeft = ()=>{
// if(tt.getMenuButtonBoundingClientRect){
// // 获取胶囊按钮的位置和尺寸信息
// let {leftIcon:{left,width}} = tt.getMenuButtonBoundingClientRect();
// // 计算标题栏高度
// return left + parseInt(width)+100;
// }else{
// // 若无法获取胶囊按钮信息,默认标题栏高度为80
// return 40;
// }
// #ifdef MP-TOUTIAO
// 获取胶囊按钮的位置和尺寸信息
let {leftIncon:{left,width}} = tt.getMenuButtonBoundingClientRect();
// 计算标题栏高度
return left + parseInt(width);
// #endif
// #ifdef MP-TOUTIAO
return 0;
// #endif
}
可以在pages目录下的页面上进行引用