先附上效果图,要达到的效果就是如图所示,把原型的导航菜单去掉,换成对应的搜索栏。
其实还是做法还是比较简单,首先讲一下实现的原理(原理明白实现起来就容易了):
1.先隐藏微信小程序自带的导航菜单;
2.自定义导航菜单样式,并设置固定定位于顶部;
接下来讲实现的具体步骤并附上代码:
1.先隐藏微信自带的导航菜单,在页面custom.json文件加上自定义导航栏的代码段(在单独设置的页面加,不要在app.json文件加,否则会影响全部的页面),如下:
{
"usingComponents": {},
"navigationStyle": "custom" //自定义导航栏
}
官方文档是这么说的:
2.在app.js文件中加上以下代码段,需要获取导航栏高度和状态栏高度,来适配不同的手机;
App({
globalData: {
navHeight:0,
navTop:0
},
onLaunch () {
var _this = this;
let menuButtonObject = wx.getMenuButtonBoundingClientRect();
wx.getSystemInfo({
success: res => {
//导航高度
let statusBarHeight = res.statusBarHeight,
navTop = menuButtonObject.top,
navHeight = statusBarHeight + menuButtonObject.height + (menuButtonObject.top - statusBarHeight) * 2;
this.globalData.navHeight = navHeight;
this.globalData.navTop = navTop; //navTop
this.globalData.windowHeight = res.windowHeight;
},
fail(err) {
console.log(err);
}
})
},
})
2.写自定义的搜索导航栏样式;
custom.wxml文件:
<!-- 自定义顶部导航 -->
<view class="flex-left navbar" style='height:{{navHeight}}px;'>
<view class="navbar-return" style='top:{{navTop}}px'>
<text class="iconfont icon-arrow-left" bindtap="goBack"></text>
</view>
<view class="navbar-title" style='top:{{navTop}}px'>
<view class="flex-left search-content">
<text class="iconfont icon-search"></text>
<input bindtap="toSearch" class="search-input" type="text" placeholder="订单搜索" placeholder-class="place-holder" />
</view>
</view>
</view>
custom.wxss文件:
/* 自定义顶部导航 */
.navbar{
width: 100%;
overflow: hidden;
position: fixed;
top: 0;
left: 0;
z-index: 10;
flex-shrink: 0;
background: #FFFFFF;
}
.navbar .navbar-title {
width: 100%;
position: fixed;
left: 70rpx;
z-index: 10;
}
.navbar .navbar-return{
width: 70rpx;
height: 60rpx;
line-height: 60rpx;
text-align: center;
position: fixed;
left: 0;
}
.navbar .icon-arrow-left{
font-size: 36rpx;
color: #333;
}
.navbar .search-content{
width: 460rpx;
height: 60rpx;
background-color: #F5F5F5;
border-radius: 10rpx;
}
.navbar .icon-search{
font-size: 40rpx;
color: #A0A0A0;
padding: 0 10rpx;
}
.navbar .search-input{
font-size: 28rpx;
color: #666;
}
custom.js文件:
const App = getApp();
Page({
data: {
// 自定义顶部导航
navHeight: App.globalData.navHeight,
navTop: App.globalData.navTop,
},
// 点击返回上级页面
goBack() {
let pages = getCurrentPages(); //获取小程序页面栈
let beforePage = pages[pages.length - 2]; //获取上个页面的实例对象
wx.navigateBack({ //返回上一页
delta: 1
})
},
})
好啦,讲到这里就结束啦~