微信小程序自定义导航栏胶囊高度适配

1,257 阅读1分钟

微信截图_20211027172402.png

设置自定义导航栏标题和微信胶囊对齐

WXML

<view class="top">
   <!-- 状态栏高度:这里需要一个空的view来占位,不然用line-height就跑偏了 -->
    <view style="height: {{stateHeight*2}}rpx"></view> 
    <!-- 导航栏高度,这里转换为了rpx -->   
    <view style="height: {{navHeight*2}}rpx; line-height: {{navHeight*2}}rpx; text-align: center; ">
      <text class="lg text-gray" class="cuIcon-back" bindtap="onNavigateBack"></text>
      订单详情
    </view>
</view>
//这里我用了框架图标,可以删掉

js

/**
   * 页面的初始数据
   */
  data: {
    navHeight: 0,
    top: 0,
    stateHeight: 0,
   
  },
//  获取状态栏信息
  int() {
    let stateHeight = 0; //  接收状态栏高度
    let navHeight = wx.getMenuButtonBoundingClientRect().height; //  获取胶囊高度
    let top = 0;
    wx.getSystemInfo({
      success(res) {
        console.log("状态栏:" + res.statusBarHeight)
        stateHeight = res.statusBarHeight;
      }
    })
    top = wx.getMenuButtonBoundingClientRect().top - stateHeight; //  获取top值
    //  然后将取到的值返回在data里面
    this.setData({
      navHeight: navHeight + top * 2, //  导航栏高度
      stateHeight: stateHeight //  状态栏高度
    })
    console.log(navHeight,stateHeight)
  },
   /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.int()
  },

css

.top{
  background: linear-gradient(90deg, #E7413C, #F86B3B);
  width: 100%;
  font-size: 32rpx;
  color: #FFF;
  position: fixed;
  top: 0;
  z-index: 6;
}