先看下效果
iPhone x端
iPhone 6/7/8端
代码实现
1.在你想自定义的页面的.json隐藏自带的头部样式(或者在全局 app.json全部隐藏)
{
"navigationStyle": "custom"
}
2.在app.js全局globalData中添加变量,保存自定义头部宽高...
// app.js
globalData: {
userInfo: null,
navBarHeight: 0, // 导航栏高度
menuRight: 0, // 胶囊距右方间距(方保持左、右间距一致)
menuTop: 0, // 胶囊距底部间距(保持底部间距一致)
menuHeight: 0, // 胶囊高度(自定义内容可与胶囊高度保证一致)
}
3.获取自定义头部的宽高
// app.js
onLaunch() {
const that = this;
// 获取系统信息
const systemInfo = wx.getSystemInfoSync();
// 胶囊按钮位置信息
const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
// 导航栏高度 = 状态栏高度 + 44
that.globalData.navBarHeight = systemInfo.statusBarHeight + 44;
that.globalData.menuRight = systemInfo.screenWidth - menuButtonInfo.right;
that.globalData.menuTop= menuButtonInfo.top;
that.globalData.menuHeight = menuButtonInfo.height;
},
4.自定义的页面获取到全局变量的数据
const app=getApp()
/**
* 页面的初始数据
*/
data: {
navBarHeight: app.globalData.navBarHeight,// 获取导航栏高度
menuRight: app.globalData.menuRigh,// 获取胶囊距右方间距(方保持左、右间距一致)
menuTop: app.globalData.menuTop,// 获取胶囊距底部间距(保持底部间距一致)
menuHeight: app.globalData.menuHeight,// 获取胶囊高度(自定义内容可与胶囊高度保证一致)
},
5.页面使用
<!-- 自定义顶部栏 -->
<view class="topSearch" style="height:{
{navBarHeight}}px;">
<text style="height:{
{menuHeight}}px; min-height:{
{menuHeight}}px; line-height:{
{menuHeight}}px; left:{
{menuRight}}px; top:{
{menuTop}}px;">天使童装</text>
<input type="text" placeholder="输入关键词搜索" style="height:{
{menuHeight}}px; min-height:{
{menuHeight}}px; margin-left: 170rpx; line-height:{
{menuHeight}}px; left:{
{menuRight}}px; top:{
{menuTop}}px;" />
</view>
6.在当前页面.wxss页面写出你需要自定义的样式即可
/* pages/home/home.wxss */
/* 头部 */
.topSearch {
width: 100%;
display: flex;
background-color: #a9a6a6;
position: fixed;
top: 0;
left: 0;
z-index: 999;
}
/* 头部title样式 */
.topSearch text {
position: absolute;
font-size: 30rpx;
font-weight: 700;
margin: 0 30rpx;
}
/* 头部input样式 */
.topSearch input {
position: absolute;
width: 350rpx;
height: 55rpx;
background-color: #f7f8fa;
border-radius: 20rpx;
color: #a9a6a6;
font-size: 28rpx;
box-sizing: border-box;
padding-left: 20rpx;
}
7.占位
因头部设置了display: flex;固定定位,脱离了文档流,为防止覆盖内容,需要定义跟自定义头部同宽高的盒子占位
<!-- 占位,高度与顶部栏一样 -->
<view style="height:{
{navBarHeight}}px;"></view>
8.最终效果
小结:
小程序自带头部导航栏非常局限,据开发文档,我们可以自定义导航栏样式,使用navigationStyle属性,属性值为custom,先隐藏自带样式,
然后根据右上角胶囊的位置来定位我们头部其他样式,wx.getMenuButtonBoundingClientRect,API会返回胶囊在页面的位置及宽高,根据胶囊的宽高和位置动态的设置我们左边定位和输入框的位置和宽度,来实现多端适配的效果