微信小程序自定义导航栏

393 阅读2分钟

一、背景

    在微信小程序平常的业务开发中,发现有两个API可以实现自定义导航栏

二、步骤

1、首先需要了解在哪里配置自定义导航栏(配置页面路径的json文件中)

image.png

2、其次需要了解两个微信小程序API的使用方式

    2.1、wx.getSystemInfo()

 作用:获取系统信息
    主要有一个参数需要在自定义导航栏中使用
    statusBarHeight:状态栏的高度

    2.2、wx.getMenuButtonBoundingClientRect()

作用:获取菜单按钮(右上角胶囊按钮)的布局位置信息。坐标信息以屏幕左上角为原点。
2.2.1width:右上角胶囊按钮的宽度 
2.2.2height:右上角胶囊按钮的高度 
2.2.3top:右上角胶囊按钮到顶部的距离 
2.2.4right:右上角胶囊按钮最右边到屏幕最左边的距离 
2.2.5bottom:右上角胶囊按钮最下边到屏幕最顶部的距离 
2.2.6、left:右上角胶囊按钮最左边的到屏幕最左边的距离

结合图文

image.png

image.png

三、自定义导航栏

3.1、实现布局

  <view
   class="custom_nav"
   :style="{
     height: navHeight + 'px',
   }"
 >
   <view
     class="custom_nav_boxs"
     :style="{
       height: barHeight + 'px',
       'line-height': barHeight + 'px',
       paddingBottom: barBottom + 'px',
     }"
   >
     <!-- 返回按钮 -->
     <view class="nav_back">
       <image src="https://i.ibb.co/nQ7sydS/image.png" mode="widthFix"></image>
     </view>
     <!-- 首页按钮 -->
     <view class="nav_home">
       <image src="https://i.ibb.co/Y8V4VX1/image.png" mode="widthFix"></image>
     </view>
     <!-- 页面title -->
     <view
       class="nav_title"
       :style="{
         height: barHeight + 'px',
         'line-height': barHeight + 'px',
       }"
       >自定义导航</view
     >
   </view>
 </view>

3.2、样式

.custom_nav {
width: 100%;
display: flex;
align-items: flex-end;
.custom_nav_boxs {
  display: flex;
  align-items: center;
  width: 100%;
  position: relative;
  .nav_back {
    display: flex;
    align-items: center;
    box-sizing: border-box;
    padding-left: 20rpx;
    image {
      width: 40rpx;
      height: 40rpx;
    }
  }
  .nav_home {
    display: flex;
    align-items: center;
    padding-left: 20rpx;
    image {
      width: 50rpx;
      height: 50rpx;
    }
  }
  .nav_title {
    max-width: 200rpx;
    position: absolute;
    font-size: 30rpx;
    font-weight: 666;
    right: 0;
    left: 0;
    text-align: center;
    margin: 0 auto;

    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}
}

3.3、js

export default {
 data() {
   return {
     navHeight: 80,
     barHeight: 0,
     barBottom: 0,
   };
 },

 onLoad() {
   // 1、获取右上角胶囊按钮的布局位置
   const rect = uni.getMenuButtonBoundingClientRect();
   // 2、获取右上角胶囊按钮的高度
   const height = rect.height;
   // 3、获取系统信息
   const systemInfo = wx.getSystemInfoSync();
   // 4、获取状态栏的高度:statusBarHeight
   const statusBarHeight = systemInfo.statusBarHeight;
   // 5、计算出自定义导航栏的高度 (为什么需要乘以2,需要胶囊也需要垂直居中,底部也需要留出间距)
   this.navHeight = (rect.top - statusBarHeight) * 2 + height + statusBarHeight;
   // 6、导航内容的高度
   this.barHeight = height;
   this.barBottom = rect.top - statusBarHeight;
 },
};

四、实现效果

image.png