微信小程序自定義導航欄

微信小程序官方文檔提供自定義導航欄API
在這裏插入圖片描述自定義導航分兩種

  • 全局配置
  • 某個頁面單獨配置
1,全局配置 修改 app.json
	window:{
		navigationStyle:custom
	}
	此時所有頁面的導航欄均修改成自定義 只剩下微信小程序自帶的膠囊按鈕
2,單獨頁面配置(需要本地調試基礎庫版本 >= 2.4.3)
	直接修改當前頁面的獨立json文件 page.json
	{
		"navigationStyle": "custom",
	}

在使用過程中 建議把自定義導航 封裝成一個組件的形式,代碼如下:

  • 調用兩個關鍵API
wx.getSystemInfo()
wx.getMenuButtonBoundingClientRect()
  • js代碼
Component({
  /**
   * 組件的屬性列表
   */
  properties: {
    title:{ // 導航欄背景顏色
      type:String,
      value: '默認標題'
    },
    bgColor:{ // 導航欄背景顏色
      type:String,
      value: 'red'
    },
    fontColor: { // 導航欄字體顏色
      type: String,
      value: 'red'
    }
  },
  lifetimes:{
    attached(){
      let _this = this;
      wx.getSystemInfo({
        success: function(res) {
          console.log(res)
          _this.setData({
            statusHeight: res.statusBarHeight
          })
        },
      })
      let btn =  wx.getMenuButtonBoundingClientRect()
      console.log(btn)
      this.setData({
        btn:btn
      })
    }
  },

  /**
   * 組件的初始數據
   */
  data: {
    statusHeight:0,
    btn:{}
  },

  /**
   * 組件的方法列表
   */
  methods: {

  }
})
  • wxml代碼
navigateBar.wxml

<view class="navbar" style="height:{{(btn.top - statusHeight) * 2 + btn.height + statusHeight}}px; width:100%; background-color:{{bgColor}}; color:{{fontColor}}">
    <view class="navbarbox flex-aic" style="width:{{btn.left}}px; margin-top:{{btn.top }}px;">
      <view class="navbar-left" style="height:{{btn.height}}px; width:{{btn.width}}px; border-radius:{{btn.width / 2}}px;">可自定義按鈕</view>
      <view class="navbar-title">{{title}}</view>
    </view>
</view>
<view class="navbar-zw"  style="height:{{(btn.top - statusHeight) * 2 + btn.height + statusHeight}}px;"></view>
  • wxss代碼
.flex-jasc{
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.flex-aic{
  display: flex;
  align-items: center;
}
.flex-jac{
  display: flex;
  justify-content: center;
  align-items: center;
}
.navbar{
  background-color: red;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 99;
}
.navbarbox{
    padding: 0 20rpx;
}
.navbar-left{
  width: 160rpx;
  height: 56rpx;
  border-radius: 28rpx;
  border: 1rpx solid #fff;
  box-sizing: border-box;
}
.navbar-title{
  width: calc(100% - 200rpx);
  text-align: center;
  text-overflow: ellipsis;
  overflow: hidden;
  box-sizing: border-box;
  white-space: nowrap;
  padding-left: 20rpx;
}

其他頁面調用

page.json
{
	"navigationStyle": "custom",
    "usingComponents":{
         "bar":"/components/navigateBar/navigateBar"
    }
}

page.wxml
<bar bgColor="skyblue" fontColor="white" title="測試標題測試標題測試標題"/>

測試結果

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章