小程序 ---- (自定义头部导航)
一、开发思路
二、实现过程
在小程序入口文件,app.js
当中,键入以下代码(好好看注释,很容易明白):
// app.js
App({
onLaunch() {
// 判断是否由分享进入小程序
let options = wx.getLaunchOptionsSync();
let scene = options.scene;
console.log(scene, '1007/1008')
// 获取胶囊按钮的高度和距离顶端的高度和标题
let menubuttonHeight = wx.getMenuButtonBoundingClientRect().height;
let menubuttonTop = wx.getMenuButtonBoundingClientRect().top;
// 获取设备顶部状态栏的高度与状态栏的间隙高度
wx.getSystemInfo({
success: (result) => {
// 套公式
let statusHeight = (menubuttonTop - result.statusBarHeight) * 2 + menubuttonHeight + result.statusBarHeight;
// 计算胶囊按钮和状态栏之间的间隙高度
let menubuttonPadding = menubuttonTop - result.statusBarHeight;
// 计算胶囊按钮中间到状态栏的距离,目的使标题文本与胶囊按钮上下居中对齐
this.globalData.menubuttonPaddingTop = menubuttonPadding + (menubuttonHeight/2);
this.globalData.navHeight = statusHeight;
},
})
},
globalData: {
share: false, // 分享默认为false
navHeight: 0, // 导航栏的高度
menubuttonPaddingTop: 0 // 标题与状态栏的间隙高度
}
})
组件内,在index.wxml
键入以下代码:
<!--components/nav/index.wxml-->
<view class="nav" style="min-height: {{navBarHeight}}px;background-color:{{bgColor}}">
// 设置返回按钮
<navigator open-type="navigateBack">
<view wx:if="{{isBackShow}}" style="padding-bottom: {{paddingTop}}px;color: {{Color}};transform: translateY({{paddingTop}}%);" class="nav-icon-back iconfont icon-fanhui"></view>
</navigator>
// 设置标题文本
<view style="padding-bottom: {{paddingTop}}px;color: {{Color}};transform: translateY({{paddingTop}}%);" class="nav-title">{{navText}}</view>
// 设置插槽,使标题更加灵活多变
<slot name="content"></slot>
</view>
设置样式:
/* components/nav/index.wxss */
/* 引入iconfont */
@import "/styles/iconfont.wxss";
.nav {
position: fixed;
top: 0%;
left: 0%;
width: 100vw;
display: flex;
justify-content: flex-start;
// 下面将文本放置到导航栏底部,再设置按钮中间到状态栏之间距离高度的margin-bottom,即可实现文本高度居中
align-items: flex-end;
color: white;
font-size: 32.5rpx;
z-index: 999999999;
}
.nav-icon-back {
margin-left: 24rpx;
color: white;
font-size: 30rpx;
}
.nav-title {
margin-left: 27rpx;
}
核心index.js
文件中的配置:
// components/nav/index.js
const app = getApp();
Component({
/**
* 启用插槽
*/
options:{
multipleSlots: true
},
/**
* 组件的属性列表
*/
properties: {
isBackShow: {
type: Boolean,
value: false
},
navText: {
type: String,
value: ''
},
bgColor: {
type: String,
value: ''
},
Color: {
type: String,
value: '#FFFFFF'
}
},
/**
* 组件的初始数据
*/
data: {
navBarHeight: app.globalData.navHeight,
paddingTop: app.globalData.menubuttonPaddingTop
},
/**
* 组件的方法列表
*/
methods: {
}
})
至此大功告成啦!去使用看看吧!接着看。
三、场景使用
既然是自定义头部导航,我的目的是全局引用的,所以要取消小程序本身的头部导航,然后在全局配置中,使用该组件,就不用每一个页面全部去引入使用了:
// app.json
"window": {
"backgroundTextStyle": "dark",
"backgroundColor": "#EEEEEE",
"navigationStyle": "custom", // 这里设置取消
"enablePullDownRefresh": false
},
"usingComponents": {
"nav": "./components/nav/index", // 全局引用自定义导航
"tabar": "./components/tabar/index" // 埋笔,下一篇讲自定义底部tabbar
}
接着在pages中随意使用吧~
<nav isBackShow="true" navText="your title" bgColor="#286EF2"></nav>