#yyds干货盘点#【愚公系列】2022年12月 微信小程序-自定义导航栏功能的实现

时间:2022-12-14 11:24:02

前言

导航栏是指位于页面顶部或者侧边区域的,在页眉横幅图片上边或下边的一排水平导航按钮,它起着链接站点或者软件内的各个页面的作用。

小程序原生导航栏的限制

  • 除了胶囊按钮以外,原生导航栏只会出现返回按钮和当用户打开的小程序最底层页面是非首页时,默认展示的“返回首页”按钮 。
  • 原生导航栏的标题文字的颜色只有黑白。
  • 布局无法改变,不能做定制。

在做自定义导航栏栏之前得去掉原生导航栏,去掉方法如下:

  • 将需要自定义navigationBar页面的page.json的navigationBarTitleText去掉。
  • 加上"navigationStyle":"custom",这样原生的导航栏就已经消失,甚至后退键也不会出现需要自定义。

一、自定义导航栏功能的实现

1.组件的封装

"use strict";
var app = getApp();

Component({
  options: {
    // 多插槽支持
    multipleSlots: true
    // ,addGlobalClass: true
  },
properties: {
  'ext-class': {
    type: String,
    value: ''
  },
    loading: {
      type: Boolean,
      value: false
    },
    active: {
      type: Boolean,
      value: false
      // ,observer: '_showChange'
    }  
  },
  data: {},
attached: function attached() {
  // 组件被加载时,计算ios、android两个平台的尺寸差异
  var _this = this;        
  //动态计算导航栏尺寸
  var isSupport = !!wx.getMenuButtonBoundingClientRect;
  var rect = wx.getMenuButtonBoundingClientRect ? wx.getMenuButtonBoundingClientRect() : null;
  wx.getSystemInfo({
      success: function success(res) {
        var ios = !!(res.system.toLowerCase().search('ios') + 1);
        var statusBarHeight=res.statusBarHeight;
        var topBarHeight=ios ? (44 + statusBarHeight) : (48 + statusBarHeight);

        _this.setData({
            ios: ios,
            topBarHeight:topBarHeight,
            statusBarHeight:statusBarHeight,
            innerWidth: isSupport ? 'width:' + rect.left + 'px' : '',
            innerPaddingRight: isSupport ? 'padding-right:' + (res.windowWidth - rect.left) + 'px' : '',
            leftWidth: isSupport ? 'width:' + (res.windowWidth - rect.left) + 'px' : ''
        }); 
        // 这是为了在外面注入wxss变量,这个设计并不太好
        // _this.triggerEvent('getBarInfo', {topBarHeight,statusBarHeight});               
      }
  });

    //back箭头处理的显示
    var pages=getCurrentPages()      
    if(pages.length>1){
      this.setData({showBack:true})
    }
  },
  methods: {
    // _showChange: function _showChange(active) {           
    //   var displayStyle = 'opacity: ' + (active ? '1' : '0') + ';-webkit-transition:opacity 0.5s;transition:opacity 0.5s;';           
    //   this.setData({
    //       displayStyle: displayStyle
    //   });
    // },
    //双击返回顶部
    doubleClick(e) {
      if (this.timeStamp && (e.timeStamp - this.timeStamp < 300)) {
        this.timeStamp = 0
        wx.pageScrollTo({
          scrollTop: 0,
          duration: 300
        })
      } else {
        this.timeStamp = e.timeStamp
      }
    }
  }
});
{
  "styleIsolation": "apply-shared",
  "component": true,
  "usingComponents": {}
}
<view class="weui-navigation-bar {{ext-class}}" bindtouchstart="doubleClick">
	<!-- 标题栏 -->
<view class="{{active ? 'navigator-active' : 'navigator-normal'}} weui-navigation-bar__inner {{ios ? 'ios' : 'android'}}" style="padding-top: {{statusBarHeight}}px;{{innerPaddingRight}};{{innerWidth}};">

		<view class='weui-navigation-bar__left' style="{{leftWidth}}">
			<slot name="left"></slot>
		</view>

		<view class='weui-navigation-bar__center'>
			<view wx:if="{{loading}}" class="weui-navigation-bar__loading"></view>
      <block wx:if="{{active}}">
			  <slot name="center"></slot>
      </block>
		</view>
	</view>
</view>
/* 微信小程序wxss中使用var变量 */
page {
  --height: 44px;
  --right: 190rpx;
}

.weui-navigation-bar {
  overflow: hidden
}
/* 
ios、android两个平台导航栏的高度不一样
ios 44px
android 48px
 */
.weui-navigation-bar .android {
  --height: 48px;
  --right: 222rpx
}

.weui-navigation-bar__placeholder {
  height: var(--height);
  background: #F8F8F8;
  position: relative;
  z-index: 50
}


.weui-navigation-bar__inner {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 5001;
  height: var(--height);
  display: flex;
  align-items: center;
  padding-right: var(--right);
  width: calc(100% - var(--right))
}

.weui-navigation-bar__inner.navigation-bar-border {
  /* border-bottom: 2rpx solid #ddd; */
}

.weui-navigation-bar__inner .weui-navigation-bar__left {
  position: relative;
  width: var(--right);
  padding-left: 15px;
  box-sizing: border-box;
  display: -webkit-box;
  display: -webkit-flex;
  display: flex;
  align-items: center;
  -webkit-box-pack: center;
}

.weui-navigation-bar__inner .weui-navigation-bar__left .btn-back {
  width: 12px;
  height: 24px;
}

.weui-navigation-bar__inner .weui-navigation-bar__left .btn-back image {
  width: 100%;
  height: 100%;
}

.weui-navigation-bar__left .btn-home {
  width: 20px;
  height: 20px;
}

.weui-navigation-bar__left .btn-back+.btn-home {
  margin-left: 50rpx;
}

.weui-navigation-bar__left .btn-home image {
  width: 100%;
  height: 100%;
}

.weui-navigation-bar__inner .weui-navigation-bar__left .weui-navigation-bar__btn_goback:active {
  opacity: .5
}


.weui-navigation-bar__inner .weui-navigation-bar__center {
  font-size: 17px;
  text-align: center;
  position: relative;
  flex: 1;
  display: -webkit-box;
  display: -webkit-flex;
  display: flex;
  align-items: center;
  -webkit-box-pack: center;
  -webkit-justify-content: center;
  justify-content: center;
  overflow: hidden;
}

.weui-navigation-bar__center text {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-top: -2px;
}

.weui-navigation-bar__inner .weui-navigation-bar__loading {
  width: 20px;
  height: 20px;
  margin-right: 5px;
  content: " ";
  animation: loading-animate 1s steps(12, end) infinite;
  background: transparent url(data:image/svg+xml;base64,PHN2ZyBjbGFzcz0iciIgd2lkdGg9JzEyMHB4JyBoZWlnaHQ9JzEyMHB4JyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMDAgMTAwIj4KICAgIDxyZWN0IHg9IjAiIHk9IjAiIHdpZHRoPSIxMDAiIGhlaWdodD0iMTAwIiBmaWxsPSJub25lIiBjbGFzcz0iYmsiPjwvcmVjdD4KICAgIDxyZWN0IHg9JzQ2LjUnIHk9JzQwJyB3aWR0aD0nNycgaGVpZ2h0PScyMCcgcng9JzUnIHJ5PSc1JyBma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knPgogICAgPC9yZWN0PgogICAgPHJlY3QgeD0nNDYuNScgeT0nNDAnIHdpZHRoPSc3JyBoZWlnaHQ9JzIwJyByeD0nNScgcnk9JzUnIGZpbGw9JyNFMkUyRTInCiAgICAgICAgICB0cmFuc2Zvcm09J3JvdGF0ZSgzMzAgNTAgNTApIHRyYW5zbGF0ZSgwIC0zMCknPgogICAgPC9yZWN0Pgo8L3N2Zz4=) no-repeat;
  background-size: 100%;
}

@keyframes loading-animate {
  0% {
    transform: rotate3d(0, 0, 1, 0deg);
  }

  100% {
    transform: rotate3d(0, 0, 1, 360deg);
  }
}



/* 激活显示的状态, 非透明,有背景色 */
.navigator-active {
  -webkit-transition: opacity 0.5s;
  transition: opacity 0.5s;
  background: #FFF;
  color: #3c3c3c;
}

.navigator-normal {
  -webkit-transition: opacity 0.5s;
  transition: opacity 0.5s;
  background: transparent;
  color: white;
}

2.使用

<navigation-bar 
  ext-class="page-navigator-bar"
  active="{{active}}"
  loading="{{loading}}">
    <view class="left" slot="left">
      <icon bindtap="goBack" class="iconfont icon-back"></icon>
      <icon bindtap="goHome" class="iconfont icon-home"></icon>
    </view>
    <view slot="center">
      <view>自定义导航标题</view>
    </view>
</navigation-bar>
Page({
  data: {
    loading: false,
    active: true
  },
  //点击back事件处理
  goBack: function () {
    wx.navigateBack();
    this.triggerEvent('back');
  },
  //返回首页
  goHome:function(){
    wx.reLaunch({
      url: '/pages/index/index'
    })
  },
})
@font-face {
  font-family: 'iconfont';  /* project id 1716930 */
  src: url('//at.alicdn.com/t/font_1716930_0fs7vun2ngmn.eot');
  src: url('//at.alicdn.com/t/font_1716930_0fs7vun2ngmn.eot?#iefix') format('embedded-opentype'),
  url('//at.alicdn.com/t/font_1716930_0fs7vun2ngmn.woff2') format('woff2'),
  url('//at.alicdn.com/t/font_1716930_0fs7vun2ngmn.woff') format('woff'),
  url('//at.alicdn.com/t/font_1716930_0fs7vun2ngmn.ttf') format('truetype'),
  url('//at.alicdn.com/t/font_1716930_0fs7vun2ngmn.svg#iconfont') format('svg');
}
.iconfont{
  font-family: 'iconfont';
}
.icon-back::after{
  content: '\e604';
  font-size: 22px;
}
.icon-home::after{
  content: '\e6f3';
  font-size: 22px;
}
.left icon:last-child{
  padding-left: 20rpx;
}

.page-navigator-bar .navigator-normal .icon-back{
  color: white;
}
.page-navigator-bar .navigator-normal .icon-home{
  color: white;
}
.page-navigator-bar .navigator-active .icon-back{
  color: black;
}
.page-navigator-bar .navigator-active .icon-home{
  color: black;
}

#yyds干货盘点#【愚公系列】2022年12月 微信小程序-自定义导航栏功能的实现