app.js代码
onLaunch() {
let _this = this;
// 自定义顶部导航 navigationBar
// const that = this;
// 获取系统信息
const systemInfo = wx.getSystemInfoSync();
// 胶囊按钮位置信息
const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
console.log('menuButtonInfo :', menuButtonInfo);
// 导航栏高度 = 状态栏到胶囊的间距(胶囊距上距离-状态栏高度) * 2 + 胶囊高度 + 状态栏高度
_this.globalData.navigationInfo.navBarHeight = (menuButtonInfo.top - systemInfo.statusBarHeight) * 2 + menuButtonInfo.height + systemInfo.statusBarHeight;
_this.globalData.navigationInfo.menuRight = systemInfo.screenWidth - menuButtonInfo.right;
_this.globalData.navigationInfo.menuBotton = menuButtonInfo.top - systemInfo.statusBarHeight;
_this.globalData.navigationInfo.menuHeight = menuButtonInfo.height;
_this.globalData.navigationInfo.menuWidth = menuButtonInfo.width;
},
globalData: {
navigationInfo: {
navBarHeight: 0, // 导航栏高度
menuRight: 0, // 胶囊距右方间距(方保持左、右间距一致)
menuBotton: 0, // 胶囊距底部间距(保持底部间距一致)
menuHeight: 0, // 胶囊高度(自定义内容可与胶囊高度保证一致)
menuWidth: 0, //胶囊宽度 (自定义的组件方便计算空余位置)
}
}
组件代码:
js
// components/navigationBar/navigationBar.js
const app = getApp();
Component({
/**
* 组件的属性列表
*/
properties: {
// defaultData(父页面传递的数据-就是引用组件的页面)
defaultData: {
type: Object,
value: {
title: "我是默认标题"
},
observer: function (newVal, oldVal) {}
}
},
/**
* 组件的初始数据
*/
data: {
...app.globalData.navigationInfo
/*
navigationHeight,
menuRight,
menuBottom,
menuHeight
*/
},
/**
* 组件的方法列表
*/
methods: {
}
})
json
{
"component": true,
"usingComponents": {}
}
wxml
<!--
隐藏原生样式
获取胶囊按钮、状态栏相关数据以供后续计算
根据不同机型计算出该机型的导航栏高度,进行适配
编写新的导航栏
引用到页面
-->
<!-- 自定义顶部栏 -->
<view class="nav-bar" style="height:{{navBarHeight}}px;">
<!-- 存放组件位置 返回按钮、搜索、菜单等、(导航栏空余位置) -->
<view class="wrapper"
style="width:calc(100% - {{menuWidth}}px - {{menuRight*3}}px );height:{{menuHeight}}px;min-height:{{menuHeight}}px; line-height:{menuHeight}}px;bottom:{{menuBotton}}px;left:{{menuRight}}px;">
<!-- 存放按钮、input、等区域 -->
</view>
</view>
<!--
内容区域:
自定义顶部栏用的fixed定位,会遮盖到下面内容,注意设置好间距
-->
<view class="content" style="margin-top:{{navBarHeight}}px;">阿斯顿发生的</view>
wxss
.nav-bar {
position: fixed;
width: 100%;
top: 0;
color: #fff;
background: rgb(102, 70, 70);
}
.nav-bar .wrapper{
position: absolute;
background-color: #fff;
}
调用组件的页面json配置
{
"usingComponents": {
"navigation-bar":"/components/navigationBar/navigationBar"
},
"navigationStyle":"custom"
}
调用标签
<navigation-bar></navigation-bar>