小程序开发日志-5、自定义导航栏

目前小程序是支持自定义导航栏的,下面讲讲如何自定义一个适配各类手机尺寸的导航栏。先看看效果图:

 

第一步,向微信声明我们要在页面中自定导航栏。

在想要自定义的page页面中的json文件中添加声明:

{
  "navigationStyle": "custom"
}

第二步,计算导航栏高度。

由于每款手机的尺寸不一样,所以,我们不能直接写死导航栏的高度,但我们可以好好利用胶囊按钮这个东西,小程序有个api:wx.getMenuButtonBoundingClientRect(),获取菜单按钮(右上角胶囊按钮)的布局位置信息。坐标信息以屏幕左上角为原点。

通过上面这个接口,来计算导航栏应该设置的高度,最好在app.js中小程序挂载时候获取。

//app.js
App({
  onLaunch: function () {
    const that = this;
    const systemInfo =  wx.getSystemInfoSync();
    //胶囊按钮位置信息
    const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
    // 导航栏高度 = 状态栏到胶囊的间距(胶囊距上距离-状态栏高度) * 2 + 胶囊高度 + 状态栏高度
    that.globalData.navBarHeight = (menuButtonInfo.top - systemInfo.statusBarHeight) * 2 + menuButtonInfo.height + systemInfo.statusBarHeight;
    that.globalData.menuRight = systemInfo.screenWidth - menuButtonInfo.right;
    that.globalData.menuBotton = menuButtonInfo.top - systemInfo.statusBarHeight;
    that.globalData.menuHeight = menuButtonInfo.height;
    that.globalData.menuTop = menuButtonInfo.top;
  },
  globalData: {
    navBarHeight: 0, // 导航栏高度
    menuRight: 0, // 胶囊距右方间距(方保持左、右间距一致)
    menuBotton: 0, // 胶囊距底部间距(保持底部间距一致)
    menuHeight: 0, // 胶囊高度(自定义内容可与胶囊高度保证一致)
    menuTop: 0, //胶囊距离顶部高度
  }
})

第三步,定义内容与胶囊按钮垂直对齐

在page下的JS文件中,引入app,然后,获取对应的数据。

const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navBarHeight: app.globalData.navBarHeight,
    menuRight: app.globalData.menuRight,
    menuBotton: app.globalData.menuBotton,
    menuHeight: app.globalData.menuHeight,
    menuTop: app.globalData.menuTop,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
   
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },
})

由于在小程序挂载的时候,我们拿到了导航栏的高度、胶囊按钮的高度、胶囊按钮距离顶部的距离,用这三个就可以做一个完美齐平的导航栏了。

<!-- 自定义头部 -->
  <view class="head-title" style="height:{{navBarHeight}}px;">
    <view class="title-text" style="height:{{menuHeight}}px;padding-top: {{menuTop}}px;">
      <picker bindchange="bindPickerChange" value="{{index}}" range="{{array}}" range-key="{{'name'}}">
        <view>{{array[index].name}}</view>
      </picker>
      <image src="/images/icon/tran_icon.png" class="tran-icon"></image>
    </view>
  </view>

wxss文件中写入:

.head-title{
  background-color: #ffffff;
}
.title-text{
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 30rpx;
}
.tran-icon{
  width: 22rpx;
  height: 13rpx;
  margin-left: 10rpx;
  margin-top: 5rpx;
}

就先写这么多,有不懂的朋友欢迎留言~~~

原文地址:https://www.cnblogs.com/liao123/p/14133581.html