微信小程序自定义Navbar自定义组件简单兼容写法

Mango
2月16日发布

前引

在小程序项目中经常有要自定义navbar的需求,网上有很多大佬分享的教程,但有的不太兼容,有的又写的比较麻烦,这里分享一种本人在用兼容性较好而且代码比较简单的一种写法。

原理解释

微信小程序navbar头部可以拆分为几部分构成:状态栏高度胶囊高度胶囊上下两侧外边距高度 。如下图所示:

image-20250216162836289

只要能取到各个部分的值,定位navbar和设置高度都会十分简单。

获取状态栏高度

const systemInfo = wx.getWindowInfo();
systemInfo.statusBarHeight

胶囊按钮高度

用胶囊按钮的bottom - top

const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
menuButtonInfo.bottom - menuButtonInfo.top

胶囊按钮的上下外边距

menuButtonInfo.top - systemInfo.statusBarHeight

完整代码

ts代码

Component({
  data: {
    navHeight: 0, // 胶囊高度 即 navbar高度
    navWidth: 0, // 显示宽度
    navMarginY: 0, // 胶囊上下外边距
    statusBarHeight: 0, // 状态栏高度
  },
  lifetimes: {
    attached() {
      const systemInfo = wx.getWindowInfo();
      const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
      this.setData({
        statusBarHeight: systemInfo.statusBarHeight, 
        navHeight: menuButtonInfo.bottom - menuButtonInfo.top,
        navMarginY: menuButtonInfo.top - systemInfo.statusBarHeight,
        navWidth: systemInfo.screenWidth - menuButtonInfo.right + menuButtonInfo.left - 10,
      })
    },
  },
})

wxml代码

<view class="nav-box" style="padding-top: {{statusBarHeight}}px;">
  <view style="height: {{navHeight}}px; margin: {{navMarginY}}px 0; "  class="navbar">
    <view>back</view>
    <view class="title">标题部分</view>
  </view>
</view>

wxss代码

.navbar {
  position: relative;
  display: flex;
  align-items: center;
  background-color: coral;
  color: #ffffff;
  padding: 0 16rpx;
  box-sizing: border-box;
}

.navbar .title {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 32rpx;
}

这只是一个介绍原理的简单示例,具体代码要根据业务需求来做出修改

© 版权声明
THE END
喜欢就支持一下吧
点赞 0 分享 收藏
评论 抢沙发
OωO
取消
SSL