微信小程序自定义搜索导航栏

  需求背景:自定义微信小程序导航栏。

  因为项目需要,要实现如京东小程序类似的搜索导航栏(下图所示搜索框在导航栏中)。参考了官方API最终实现了该有的效果,顺便把此次实现的思路和代码记录下来。

一、拆解分析

  按照正常的导航栏拆解来进行计算自定义导航栏的高度。

  根据下图所示可以得到导航栏的高度等于:手机状态栏的高度 + 胶囊按钮高度(途中标注菜单栏)+ 以及胶囊按钮的上下边距。

  根据微信 API - wx.getMenuButtonBoundingClientRect 可以得到胶囊按钮的坐标和高宽等信息,详见文档。

  再根据微信 API -  wx.getSystemInfo(Object object)  获得状态栏高度 — statusBarHeight。

  然后计算出边距为:margin = top(胶囊按钮上边界坐标) - statusBarHeight,

  最终得到导航栏的高度为:customBarHeight = height + statusBarHeight + (margin * 2)

  知道这些信息剩下的就是实现了,下面是全部实现代码。

二、代码实现

1、json文件设置

"navigationStyle": "custom",

2、JS代码部分:需要的data和设置值

  data: {
    navHeight: '',
    statusBarHeight: 0, // 状态栏高度
    searchMarginTop: 0, // 搜索框上边距
    searchWidth: 0, // 搜索框宽度
    searchHeight: 0 // 搜索框高度
  },
  onLoad: function () {
    let menuButtonInfo = wx.getMenuButtonBoundingClientRect()
    const { top, width, height, right } = menuButtonInfo
    wx.getSystemInfo({
      success: (res) => {
        const { statusBarHeight } = res
        const margin = top - statusBarHeight
        this.setData({
          statusBarHeight: statusBarHeight,
          navHeight: (height + statusBarHeight + (margin * 2)),
          searchMarginTop: statusBarHeight + margin, // 状态栏 + 胶囊按钮边距
          searchHeight: height,  // 与胶囊按钮同高
          searchWidth: right - width - 30 // 胶囊按钮右边坐标 - 胶囊按钮宽度 = 按钮左边可使用宽度,再减去30两边间距
        })
      },
    })
  },

3、wxml代码

<view class="search-input" style="height:{{navHeight}}px;padding-top:{{searchMarginTop}}px;">
    <view class="flex between input-box" style="height:{{searchHeight}}px; {{searchWidth}}px;">
      <i class="iconfont cs-search c9 mr10" bindtap="search"></i>
      <input class="v-expand f14 c3" value="{{search}}" placeholder="{{placeholder}}" placeholder-class="f14 c9" bindinput="inputValue" bindconfirm="search"/>
    </view>
  </view>

4、css代码:样式控制及主要有吸顶的操作。

.search-input{
  position: sticky;
  box-sizing: border-box;
  background: #fff;
  top: 0;
}
.input-box{
  box-sizing: border-box;
  padding: 0 30rpx;
  margin: 0 30rpx;
  background: #f7f7f7;
  border-radius: 30rpx;
}
原文地址:https://www.cnblogs.com/goloving/p/14627146.html