微信小程序自定义头部

1.在对应界面的json文件,将navigationStyle属性设置为“custom”

"navigationStyle":"custom"

2. 状态栏的高度可以通过 wx.getSystemInfo() 获取。

胶囊按钮的信息可以通过 wx.getMenuButtonBoundingClientRect() 获取。

导航栏高度=状态栏高度+胶囊按钮的高度+(胶囊按钮距离顶部的距离-状态栏的高度)*2。

由于胶囊按钮是原生组件,为表现一致,其单位在各个系统都为 px,所以自定义导航栏高度的单位都必须是 px,才能完美适配。

wxml

<view class="header-box">
        <view style="height:{{capsuleHeight}}px;top:{{capsuleTop}}px" class='back'>
            <van-icon name="arrow-left" color="#333" bindtap='navBack' size="50rpx" />
        </view>
        <view class="nav-title" style="height:{{capsuleHeight}}px;top:{{capsuleTop}}px">物联网数据</view>
        <image src="/static/images/news.png" mode="scaleToFill"></image>
</view>

wxss:

.header-box{
  width: 100%;
  position:relative;
}
.header-box image {
  width: 100%;
}
.other-box{
  position: absolute;
  top: 370rpx;
}
.back{
  position: absolute;
  left: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
.nav-title{
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  font-size: 32rpx;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
}

js

onLoad(){
    wx.getSystemInfo({
        success: res => {
          this.setData({
            statusBarHeight:res.statusBarHeight // 获取状态栏的高度
          })
        }
      })
      // 获取胶囊信息
      this.data.capsule = wx.getMenuButtonBoundingClientRect()  // 获取胶囊按钮的信息
      this.setData({
        capsuleTop:this.data.capsule.top, //  胶囊距离屏幕顶部的距离
        capsuleHeight:this.data.capsule.height, // 胶囊高度
      })
      this.setData({
         // 导航栏高度=状态栏高度+胶囊按钮的高度+(胶囊按钮距离顶部的距离-状态栏的高度)*2
        navbarHeight:(this.data.capsule.top-this.data.statusBarHeight)*2+this.data.capsule.height+this.data.statusBarHeight // 导航栏高度
      })
}

该页面自定义头部,也支持分享好友,导致分享出去点左上角的返回没有反应

// 自定义导航返回按钮
navBack(){  
    let pages = getCurrentPages(); //获取所有页面
        if (pages.length <= 1){
        // 返回首页
            wx.switchTab({
             url: '/pages/index/index',
            });
        } else {
        // 返回上一页
          wx.navigateBack({
            delta: 1,
          });
        }      
  }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值