微信小程序自定义头部

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

复制代码
"navigationStyle":"custom"
  1. 状态栏的高度可以通过 wx.getSystemInfo() 获取。

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

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

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

wxml

html 复制代码
<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:

css 复制代码
.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

javascript 复制代码
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 // 导航栏高度
      })
}

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

javascript 复制代码
// 自定义导航返回按钮
navBack(){  
    let pages = getCurrentPages(); //获取所有页面
        if (pages.length <= 1){
        // 返回首页
            wx.switchTab({
             url: '/pages/index/index',
            });
        } else {
        // 返回上一页
          wx.navigateBack({
            delta: 1,
          });
        }      
  }
相关推荐
HERR_QQ16 小时前
【unify】unify的微信小程序开发学习 (to be continued)
学习·微信小程序·小程序
racerun1 天前
小程序导航设置更多内容的实现方法
小程序
说私域1 天前
基于开源AI智能名片链动2+1模式S2B2C商城小程序的超级文化符号构建路径研究
人工智能·小程序·开源
mg6681 天前
微信小程序入门实例_____快速搭建一个快递查询小程序
微信小程序·小程序
程序员柳1 天前
基于微信小程序的校园二手交易平台、微信小程序校园二手商城源代码+数据库+使用说明,layui+微信小程序+Spring Boot
数据库·微信小程序·layui
Jyywww1211 天前
微信小程序学习笔记
笔记·学习·微信小程序
The_era_achievs_hero1 天前
微信小程序41~50
微信小程序·小程序
走,带你去玩2 天前
uniapp 微信小程序水印
微信小程序·小程序·uni-app
是一碗螺丝粉2 天前
🔥 微信H5视频自动播放终极秘籍:WeixinJSBridge竟是官方“通行证”?
微信小程序