2

微信小程序自定义导航栏与胶囊对齐方案

 2 years ago
source link: https://segmentfault.com/a/1190000041086113
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

在网上看过一些其他人的方案,和我设想的向胶囊看齐思路(这个不应该是最简单清晰的方案么?)都不一样,所以就自己整了一个方案了。

要实现自定义导航栏与胶囊对齐,如下图如示,只需要获取导航栏高度,及导航栏距上的位置(其实就是状态栏高度),再通过css布局就完成任务了。这个方案应该是最简单易懂的方案了。
如果有更复杂的布局需要,都以导航容器为基准去扩展就行了。

image.png

获取距上和高度

获取距上,也即状态栏高度,调用 wx.getSystemInfoSync api 可以拿到:

// 获取距上
const barTop = wx.getSystemInfoSync().statusBarHeight

getSystemInfoSync 参考(注意:小程序基础库版本不低于 1.9.6): https://developers.weixin.qq....

导航栏高度

从上面的图里我们可以看到导航栏高度是由胶囊高度+胶囊上下边距。
胶囊上下边距是一样大的,通过胶囊top-状态栏高度就可以得到上边距。
胶囊信息通过 wx.getMenuButtonBoundingClientRect api 可以拿到。

// 获取胶囊按钮位置信息
const menuButtonInfo = wx.getMenuButtonBoundingClientRect()
// 获取导航栏高度
const barHeight = menuButtonInfo.height + (menuButtonInfo.top - barTop) * 2

getMenuButtonBoundingClientRect 参考 (注意: 小程序基础库版本不低于 2.15.0):https://developers.weixin.qq....

占位容器高度

一般来说自定义导航栏是要固定在页面最上面的,所以得有个占位元素来占距位置,不然页面最上面正常内容就会被导航栏遮住。所以导航栏外面应该再加个占位容器,高度 = 导航栏高度 + 距上。

const placeholderHeight = barHeight + barTop

js 部分:

// 如果需要多个页面都引入自定义组件,那建一个 Behavior 放里面
Page({
  data: {
    // bar (title这一条) 距
    barTop: 0,
    // bar 高度, bar 是 fixed
    barHeight: 0,
    // 占位高度,不是 fixed,这个高度实际就是 barTop + barHeight
    placeHolderHeight: 0
  },
  onLaunch () {
    // 获取距上
    const barTop = wx.getSystemInfoSync().statusBarHeight
    // 获取胶囊按钮位置信息
    const menuButtonInfo = wx.getMenuButtonBoundingClientRect()
    // 获取导航栏高度
    const barHeight = menuButtonInfo.height + (menuButtonInfo.top - barTop) * 2
    this.setData({
      barHeight,
      barTop,
      placeHolderHeight: barHeight + barTop
    })
  }
})

wxml 部分。要注意的是 占位容器是正常元素顶不到屏幕最上面,所以给它加白色背景色是遮不住状态栏的,得在 header 上加,因为 header是 fixed 元素可以顶到屏幕最上面,然后top用在padding上。Perfect!

<view style="height: {{placeHolderHeight}}px;">
  <view class="header" style="height: {{ barHeight }}px; padding-top: {{barTop}}px">
    <text>这是标题</text>
  </view>
</view>

wxss 部分

.header {
  background-color: #fff;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
}

设置小程序基础版本库

getMenuButtonBoundingClientRect 需要小程序基础库版本不低于 2.15.0,登录微信小程序管理后台,在最下面的 设置-基本设置-功能设置-基础库最低版本设置 里可以设置。
image.png

自定义导航栏配置

要自定义导航栏,需要在页面的 json 文件里增加配置:

// xxx.json
{
  "navigationStyle": "custom"
}

https://developers.weixin.qq....


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK