微信小程序自定义头部

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,
          });
        }      
  }
相关推荐
说私域1 小时前
开源AI智能名片链动2+1模式商城小程序在淘宝首页流量生态中的应用与影响研究
人工智能·小程序·开源
jqpwxt2 小时前
启点创新智慧景区小程序系统,景区智能化售票系统,景区购票管理系统
小程序
高林雨露2 小时前
App拉起小程序无法正常返回app 排查坑道
java·小程序
2501_9160074719 小时前
苹果手机iOS应用管理全指南与隐藏功能详解
android·ios·智能手机·小程序·uni-app·iphone·webview
Gracemark20 小时前
H5回调页开发与调试复盘
微信小程序
yogalin199320 小时前
微信小程序代码复用技巧
性能优化·微信小程序
求学中--20 小时前
进阶实战:构建一个完整的微信小程序博客系统(含云开发与状态管理)
微信小程序·小程序
2501_915106321 天前
全面理解 iOS 帧率,构建从渲染到系统行为的多工具协同流畅度分析体系
android·ios·小程序·https·uni-app·iphone·webview
计算机毕设指导61 天前
基于微信小程序的宠物走失信息管理系统【源码文末联系】
java·spring boot·mysql·微信小程序·小程序·tomcat·宠物
2501_916008891 天前
iOS 能耗检测的工程化方法,构建多工具协同的电量分析与性能能效体系
android·ios·小程序·https·uni-app·iphone·webview