最近做的项目涉及相应的页面显示相应的顶部标题,所以就需要自定义头部导航了。
首先新建一个顶部导航公用组件topnav,导航高度怎么计算?
1.wx.getSystemInfo 和 wx.getSystemInfoSync 获取机器信息2.screenHeight - windowHeight 计算标题栏高度3.标题栏高度'iPhone': 64,'iPhone X': 88,'android': 68
app.js
//app.jsApp({ onLaunch: function () { var that = this wx.getSystemInfo({ success: function (res) { that.globalData.platform = res.platform let totalTopHeight = 68 if (res.model.indexOf('iPhone X') !== -1) { totalTopHeight = 88 } else if (res.model.indexOf('iPhone') !== -1) { totalTopHeight = 64 } that.globalData.statusBarHeight = res.statusBarHeight that.globalData.titleBarHeight = totalTopHeight - res.statusBarHeight }, failure() { that.globalData.statusBarHeight = 0 that.globalData.titleBarHeight = 0 } }) })
还需更改配置app.json
"window": { "backgroundTextStyle": "light", "navigationBarBackgroundColor": "#15ae67", "navigationBarTitleText": "微信小程序", "navigationBarTextStyle": "white", "navigationStyle": "custom" //自定义导航栏配置 }
topnav.wxml
{ {innerTitle}}
topnav.json
{ "component": true}
topnav.js
const app = getApp()Component({ properties: { // 这里定义了innerText属性,属性值可以在组件使用时指定 innerTitle: { type: String, value: '头部标题' }, isShowBack: { type: String, value: "true" } }, data: { // 这里是一些组件内部数据 someData: { statusBarHeight: app.globalData.statusBarHeight, titleBarHeight: app.globalData.titleBarHeight } }, methods: { // 这里是一个自定义方法 goback: function () { wx.navigateBack({ delta: 1, }) } }})
topnav.wxss
.ico-back{ width: 36rpx; height: 36rpx; background-size: contain; background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACQAAAAkCAYAAADhAJiYAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyZpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM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3UGkwaSItJAY1gwkGjmFCQBRMGsmJCQB4MHOTFQEEIDAyEwkBASIwGRIrFr/XBZy03InpbQFJcFHW8Gu+2nnmUiFAM2daLzz/DVtHtaSc1DIX87SEo9MLoRkVsHS5U1OZqRkUeP0yo6APaMCrjCDuEyjrkq1GZ1yAVKvui2EXNuEqLqFnJBgk1LR3TQi08OWF1RqmyH8SAtB0yvgIMAGA41d9Fo4AZAAAAAElFTkSuQmCC); background-repeat: no-repeat; background-position-x: 20rpx;}.hh-header { position: fixed; top: 0; width: 100%; background-color: #14ae66; z-index: 99;}.hh-title{ font-size: 38rpx; text-align: center; color: #fff; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;}.title-bar { display: flex; justify-content: space-between; align-items: center;}.hh-nav-right{ width: 116px;}.hh-nav-back{ width: 116px;}
这样组件就写好了 只需要在你每个页面里面用这个组件传不同的值就可以了。
index.wxml
//显示返回按钮
<component-topnav inner-title="我的管理" is-show-back="false"></component-topnav> //不显示返回按钮
index.js
//获取应用实例const app = getApp()Page({ data: { motto: 'Hello World', userInfo: {}, title:'自定义导航标题' },})
index.json
{ "usingComponents": { "component-topnav": "/pages/component/topnav" }}