微信小程序自定义导航栏

微信小程序官方文档提供自定义导航栏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="测试标题测试标题测试标题"/>

测试结果

在这里插入图片描述

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