微信小程序开发中自定义自适应头部导航栏

1.在app.js文件中获取一些数据

//app.js
App({
  onLaunch: function () {
  
    const that = this;
    // 获取系统信息
    const systemInfo = wx.getSystemInfoSync();
    // 胶囊按钮位置信息
    const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
    // 导航栏高度 = 状态栏到胶囊的间距(胶囊距上距离-状态栏高度) * 2 + 胶囊高度 + 状态栏高度
    that.globalData.navBarHeight = (menuButtonInfo.top - systemInfo.statusBarHeight) * 2 +  menuButtonInfo.height + systemInfo.statusBarHeight;
    that.globalData.menuRight = systemInfo.screenWidth - menuButtonInfo.right;
    that.globalData.menuBottom = menuButtonInfo.top - systemInfo.statusBarHeight;
    that.globalData.menuHeight = menuButtonInfo.height;

  },
  globalData: {
    userInfo: null,
    navBarHeight: 0, // 导航栏高度
    menuRight: 0, // 胶囊距右方间距(方保持左、右间距一致)
    menuBottom: 0, // 胶囊距底部间距(保持底部间距一致)
    menuHeight: 0, // 胶囊高度(自定义内容可与胶囊高度保证一致)
  }
})

2.  需要在哪个页面进行自定义导航栏设置就引入这些数据

在页面的json文档中设置 :      "navigationStyle": "custom"

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {

    navBarHeight: app.globalData.navBarHeight,
    menuRight: app.globalData.menuRight,
    menuBottom: app.globalData.menuBottom,
    menuHeight: app.globalData.menuHeight,
  },


})
<!-- 头部导航栏 -->
<view class="nav-bar" style="height:{{navBarHeight}}px;">
  
  <view bindtap="goCompany" class="personIcon" style="bottom:{{menuBottom}}px;">
    <open-data type="userAvatarUrl" class="avatarOpen" ></open-data>
  </view>
  <view class="title" style="height:{{menuHeight}}px;bottom:{{menuBottom}}px;line-height:{{menuHeight}}px;">
    登记信息
  </view>
</view>

<!-- 站位 防止内容区上到头部 -->
<view style="height:{{navBarHeight}}px;"></view> 

3.效果显示

原文地址:https://www.cnblogs.com/cyf666cool/p/14549487.html