微信小程序自定义搜索导航栏
需求背景:自定义微信小程序导航栏。
因为项目需要,要实现如京东小程序类似的搜索导航栏(下图所示搜索框在导航栏中)。参考了官方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;width: {{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;
}
分类:
微信小程序/微信/阿里云相关开发
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律