小程序导航条自定义,高度自适应iphoneX等刘海手机和其他手机,开启导航自定义需要在app.json文件里将window的 navigationStyle属性设置为: custom,开启导航自定义可以丰富其样式,下面是代码~
//该文件是app.json,开启后默认就没有导航了 "window": { "navigationStyle": "custom" }
没有导航只有我们我要新建一个,我们把它作为组件,这样小程序的其他页面就都可以引入了,新建一个 Title 的组件,但是这个组件的高度我们要根据不同的手机去适配,如果是iphoneX,一般刘海手机是88px,其他是64px,但没有标准,主要还是看手机型号,微信提供一个可以获取的导航条加状态栏高度的接口 wx.getSystemInfo
//在app.js 的onLaunch 方法里面 wx.getSystemInfo({ success:e=>{ this.globalData.statusBar = e.statusBarHeight; let custom = wx.getMenuButtonBoundingClientRect(); this.globalData.custom=custom; this.globalData.customBar=custom.bottom+custom.top-e.statusBarHeight; } }) //e.statusBarHeight 这是状态栏高度,一般手机为 20px ,iphoneX 为44px,我们就是根据这个来设置导航的高度 //在Title的组件中 const app = getApp() Component({ /** * 组件的初始数据 */ data: { full:false, statusBar:app.globalData.statusBar, customBar:app.globalData.customBar } })
组件的 wxml 文件
<view class="title" style="height:{{customBar}}px;padding-top:{{statusBar}}px;"> <view class='con' style="height:{{customBar-statusBar}}px;"> <!-- 这个是是否显示返回键,是一个图片,如果没有图片地址会报错,一般根据组件传值来显示 --> <navigator open-type="navigateBack" class="left" wx:if="{{true}}" > <image src="../../assets/icon/left.png"></image> </navigator> <!-- 这个是标题的内容,一般也是通过组件传值来显示 --> <view class="right">我是标题</view> </view> </view> <!-- 这个是占位的,因为我们把title设置成fixed定位,所以需要一个占位,不然会往上顶 --> <view style="height:{{customBar}}px;width:100%;"></view>
组件的css文件
/*这是组件的样式*/ .title{ width:100%; box-sizing: border-box; background: #fff; position:fixed; top:0; left:0; z-index: 9999; } .con{ width:100%; display: flex; position:relative; } .title .left{ position:absolute; left:0; top:0; width:70rpx; height:100%; display:flex; justify-content: center; align-items: center; } .title .left image{ width:50rpx; height:50rpx; } .title .right{ flex:0 0 calc(100% - 140rpx); width:calc(100% - 140rpx); margin:0 auto; color:#000; font-weight:bold; display: flex; align-items: center; justify-content: center; padding-right:calc(100%-140rpx); font-size:38rpx; letter-spacing: 2rpx; pointer-events: none; text-overflow: ellipsis; white-space:normal; overflow:hidden; }
其他手机的效果图
iphoneX手机效果图
我们把这个组件强化一下,让他可以进行组件传值
组件的js文件
//把这个放在组件的 properties的字段里面 properties: { title:{ type:String //这个是标题 }, isBack:{ //这个是 是否显示返回按钮,如果不传值就默认显示 type:Boolean, value:true } },
组件的 wxml 文件
<view class="title" style="height:{{customBar}}px;padding-top:{{statusBar}}px;"> <view class='con' style="height:{{customBar-statusBar}}px;"> <navigator open-type="navigateBack" class="left" wx:if="{{isBack}}" > <image src="../../assets/icon/left.png"></image> </navigator> <view class="right">{{title}}</view> </view> </view> <view style="height:{{customBar}}px;width:100%;"></view>
调用方式
先在调用的页面声明该组件
组件的json文件
{ "usingComponents": { "Title": "../../components/Title/Title", //根据你的实际路径去引入 } }
调用
<Title title="我的地址" />
效果图
取消返回键
<Title title="我的地址" isBack="{{false}}" />