小程序 - 如何自定义导航栏

思路

 

自定义导航栏高度组成:状态栏(绿色部分)、导航栏(蓝色部分)

状态栏

通过调用 wx.getSystemInfoSync 获取

const res = wx.getSystemInfoSync()
this.setData({
   statusBarHeight:res.statusBarHeight
})

导航栏

通过获取右上角胶囊的位置信息计算,navBarPadding为导航栏上下的间隙 

let res = wx.getMenuButtonBoundingClientRect()
let navBarPadding = (res.top - this.data.setStatusBarHeight) * 2 
this.setData({
   navBarHeight: res.height + navBarPadding
})

代码

app.js:

App({
  onLaunch () {
     this.setStatusBarHeight()
     this.setNavBar()
  },
  //设置系统状态栏高度
  setStatusBarHeight(){
      try {
        const res = wx.getSystemInfoSync()
        this.globalData.statusBarHeight = res.statusBarHeight
      }catch(error){
        console.log(error)
      }
  },
  //设置导航栏height
  setNavBar(){
      let res = wx.getMenuButtonBoundingClientRect()
      let navBarPadding = (res.top - this.globalData.statusBarHeight) * 2 
      this.globalData.navBarHeight = res.height + navBarPadding
  }, 
  globalData: {
    statusBarHeight: 20,
    navBarHeight: 44
  }
})

 

wxml:

<view class="top-bar-wrap">
    <view class="top-bar-main" style="padding-top:{{statusBarHeight}}px;height:{{navBarHeight}}px">
        自定义导航栏
    </view>
</view>

wxss:

.top-bar-wrap{
    z-index: 9999;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
}
.top-bar-main{
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    color:#fff;
}

js:

const app = getApp()
Component({
data: { statusBarHeight: app.globalData.statusBarHeight, navBarHeight: app.globalData.navBarHeight } })

最后

setStatusBarHeight、setNavBar这两个方法最好写到app.js中,获取好放在app.globalData中,这两个高度可能不止自定义导航栏需要用到。

比如使用了自定义导航栏的页面,因为自定义导航栏是fixed定位脱离文档流,导致整个页面就会上移,所以要给页面加上padding-top,高度跟自定义导航栏的高度一致,即 statusBarHeight + navBarHeight。

posted @ 2019-10-20 11:36  WahFung  阅读(467)  评论(1编辑  收藏  举报
Live2D