实现自定义顶部导航栏需要借助两个微信api
let custom = wx.getMenuButtonBoundingClientRect();
获取菜单按钮(右上角胶囊按钮)的布局位置信息。坐标信息以屏幕左上角为原点。
let { windowWidth } = wx.getSystemInfoSync()
获取设备信息
把代码贴下面了,希望能给一些小小小小小白们带来一些灵感吧
在app.js onLaunch中计算出顶部栏的位置
App({
onLaunch: function () {
let custom = wx.getMenuButtonBoundingClientRect();//菜单按钮
let { windowWidth } = wx.getSystemInfoSync()
this.globalData.navTopBar = {
//整体顶部高度
customBar: custom.bottom + 10,
//工具栏定位
navTop: custom.top,
//工具栏宽
topWdith: windowWidth - (windowWidth - custom.left),
//工具栏高
topHeight: custom.bottom - custom.top,
//标题容器宽度
titleWdith: windowWidth - (windowWidth - custom.left) * 2,
//返回按钮容器宽度
btnWdith: windowWidth - custom.left,
//返回按钮容器padding
btnPadd: windowWidth - custom.right
}
//注意以上结果单位全部为px!!
},
globalData: {
navTopBar:{}
}
})
组件wxml代码主要就是一些简单的布局
<view class="nav-box" style="height:{{customBar}}px;">
<view class="nav-top" style="top:{{navTop}}px;width:{{topWdith}}px;height:{{topHeight}}px">
<!-- 按钮部分 -->
<view class="nav-btn" style="height:100%;width:{{btnWdith}}px;padding-left:{{btnPadd}}px">
<view class="nav-btn-item" wx:if="{{isBtn}}" hover-class="none" hover-stop-propagation="false" style="width:{{btnWdith-btnPadd}}px;border-radius: {{topHeight/2}}px;">
<view class="nav-btn-img" catchtap="back">
<image src="/images/back1.png" mode="heightFix" ></image>
</view>
<view class="nav-btn-view">
</view>
<view class="nav-btn-img" catchtap="home">
<image src="/images/home1.png" mode="heightFix" ></image>
</view>
</view>
</view>
<!-- 标题部分 -->
<view class="nav-title" style="height:100%;width:{{titleWdith}}px">首页</view>
</view>
</view>
<!-- 实体块 -->
<view style="height:{{customBar}}px;"></view>
组件js部分
// components/topBar/topBar.js
const app = getApp();
Component({
/**
* 组件的属性列表
*/
properties: {
//参数是否展示返回按钮
isBtn: {
type: Boolean,
value: false
}
},
/**
* 组件的初始数据
*/
data: {
...app.globalData.navTopBar
},
/**
* 组件的方法列表
*/
methods: {
back() {
console.log("返回")
let pages = getCurrentPages()
console.log(pages)
if (pages.length >= 2) {
wx.navigateBack({
delta: 1,
})
}
}, home() {
console.log("去首页")
wx.redirectTo({
url: '/pages/index/index',
})
}
}
})
css部分
view, scroll-view, swiper, button, input, textarea, label, navigator, image {
box-sizing: border-box;
}
.nav-box{
background: #1e52d8;
color: aliceblue;
width: 750rpx;
position: relative;
display: flex;
position: fixed;
top:0;
z-index:999;
}
.nav-top{
position: absolute;
display: flex;
}
.nav-title{
display: flex;
justify-content: center;
align-items: center;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
}
.nav-btn{
display: flex;
align-items: center;
}
.nav-btn-item{
flex: 1;
display: flex;
height: 100%;
background-color:rgb(248, 248, 248,0.5);
align-items: center;
justify-content: space-around;
}
.nav-btn-img{
flex: 1;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.nav-btn-img image{
height: 70%;
}
.nav-btn-view{
height: 50%;
border-left: 1rpx solid rgb(248, 248, 248,0.8);
}