uniapp标题水平对齐微信小程序胶囊按钮及适配
- 状态栏高度
 - 胶囊按钮的信息
 - 计算顶部边距
 - 模板
 - 样式
 
标签加样式加动态计算实现效果
 
状态栏高度
获取系统信息里的状态栏高度
const statusBarHeight = uni.getSystemInfoSync().statusBarHeight;//系统信息里的状态栏高度
 
胶囊按钮的信息
用到胶囊按钮的top、height
const menuButtonInfo= uni.getMenuButtonBoundingClientRect();//胶囊按钮信息
 
计算顶部边距
上下有边距所以要除以2
 
 
顶部边距 = 胶囊按钮的top - (胶囊按钮的高度 - 状态栏高度) / 2
const titleTop = menuButtonInfo.top - (menuButtonInfo.height - statusBarHeight) / 2;//标题父元素边距高度
 
模板
<view  :style="{paddingTop: titleTop + 'px'}">
	<view class="main-title" :style="{height: sBarHeight +'px'}">{{tenantName}}</view>
</view>
 
到这已经框对齐胶囊按钮了,但是字体内容还没对齐
 
样式
写样式对齐
.main-title {
  /*必要 对齐胶囊按钮*/
  display: flex;
  align-items: center;
  }
 
vue2代码
 titleTop: 0,
 statusBarHeight: 0,
  onReady() {
    let that = this;
	// 获取胶囊按钮位置信息
    const menuButtonInfo = uni.getMenuButtonBoundingClientRect();
    const { top, height } = menuButtonInfo;
    const statusBarHeight = uni.getSystemInfoSync().statusBarHeight;
    // 计算标题需要偏移的位置
    const titleTop = top + (height - statusBarHeight) / 2;
    this.titleTop = titleTop;//设置标题顶部距离
    this.statusBarHeight = statusBarHeight;//设置状态栏高度
  },
  
<view class="indexPage" :style="{paddingTop: titleTop + 'px'}">
    <view class="main-title" :style="{height: sBarHeight +'px'}">{{tenantName}}</view>
</view>
.main-title {
  /*必要 对齐胶囊按钮*/
  display: flex;
  align-items: center;
}
 
vu3代码
const sBarHeight = ref<any>(uni.getSystemInfoSync().statusBarHeight)
const titleTop = ref<any>(0)
import {onLoad,  } from '@dcloudio/uni-app'
onLoad(async (options: any) => {
    const menu = uni.getMenuButtonBoundingClientRect()
    titleTop.value = menu.top + (menu.height - sBarHeight.value) / 2;//顶部标题对齐
    console.log("✈️menu===", menu);
  })
<view class="indexPage" :style="{paddingTop: titleTop + 'px'}">
    <view class="main-title" :style="{height: sBarHeight +'px'}">{{tenantName}}</view>
</view>
.main-title {
  /*必要 对齐胶囊按钮*/
  display: flex;
  align-items: center;
}
                


















