小程序导航栏透明,精准设置小程序自定义标题的高度和定位

场景

常见场景为ui小姐姐为页面顶部设计了漂亮的图片例如我们的
在这里插入图片描述
好多小伙伴会设置隐藏系统的标题栏,但是自定义标题栏因为安卓和ios手机的兼容性问题,经常出现有的手机上标题和右侧按钮不能水平对齐的问题,接下来我用一种简单的方法来处理这兼容性问题

设置页面标题栏为自定义模式

进入目标页面的page.json 设置navigationStyle

{
  "navigationStyle": "custom",
}

这一步很简单,网上一大堆教程,接下来上干货,先熟悉下几个概念

一些概念 - 重点

  1. statusBarHeight:状态栏高度(小程序可获取),是指顶部显示手机信号,时间,电量的那一个小的状态条的高度。如图红色部分。
  2. titleBarHeight:标题栏高度(小程序获取不到),是从状态栏的底部开始的,到标题栏的底部的高度为止。如图绿色部分。 安卓48px ios44px
  3. wx.getMenuButtonBoundingClientRect():获取菜单按钮(右上角胶囊按钮)的布局位置信息。 主要由height、top

接下来我们主要用胶囊按钮的高度和top来处理我们自定义标题栏的问题
在这里插入图片描述

解决方案

自定义标题栏,需要知道标题栏的高度和定位、页面主题的顶部的padding-top,计算方式如下

自定义标题:定位
  top:胶囊top
  height: 胶囊height

页面顶部空白高度
	页面paddingTop = 胶囊top +  胶囊height

详细代码

框架:taro
理解思路就好,用哪个小程序框架都一样,删除了无用的代码

util.js

export default {
  // 微信右上角胶囊按钮的参数
  jnbtn() {
    let jn = Taro.getMenuButtonBoundingClientRect();
    let obj = {
      width: jn.width,
      height: jn.height,
      top: jn.top,
      pageTop: jn.top + jn.height
    }
    return obj;
},

主页面

import { useCallback,useState } from "react";
import { View, Text, Button, Image } from "@tarojs/components";
import { useEnv, useNavigationBar, useModal, useToast } from "taro-hooks";
import './commission.less'
import { AtIcon } from 'taro-ui'
import util from '../../util/util'
import MyTitle from '../../components/myTitle'
const Index = () => {
  let jnbtn = util.jnbtn();

  return (
    <View className="page commipage relative">
      // 自定义标题栏
      <MyTitle title='佣金' back={true}/>
      // 设置页面主题上边的paddingTop
      <View className="pagetop" style={{ paddingTop: `${jnbtn.pageTop}px` }}>
        <Image className='yingbi' src={`${util.oss}/coin.svg`} mode='widthFix'></Image>
      </View>
    </View>
  );
};

export default Index;

自定义标题栏组件

高级程序员要经常封装组件,方便复用,哈哈

import { View } from "@tarojs/components";
import './index.less'
import { AtIcon } from 'taro-ui'
import util from '../../util/util'

const Index = (props) => {
  let jnbtn = util.jnbtn();
  const {title='', back='' }=props;

  return (
    // 重点
    <View className="mytitlew center-v" 
      style={{ top: `${jnbtn.top}px`, height: `${jnbtn.height}px` }}>
      {back && <View className="tback center-v"> <AtIcon value='chevron-left' size='20' color='#333'></AtIcon> </View>}
      {title && <View className="title center">{title}</View>}
    </View>
  );
};

export default Index;

至此完美解决小程序自定义标题栏的兼容性问题,亲测很实用。
创作不易,有帮到小伙伴出坑请打赏几毛钱,蟹蟹
在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值