微信小程序自定义navigationBar顶部导航栏适配所有

navigationBar相信大家都不陌生把?今天我们就来说说自定义navigationBar,把它改变成我们想要的样子(搜索框+胶囊、搜索框+返回按钮+胶囊等)。

思路

隐藏原生样式

获取胶囊按钮、状态栏相关数据以供后续计算

根据不同机型计算出该机型的导航栏高度,进行适配

编写新的导航栏

引用到页面

正文

一、隐藏原生的navigationBar

window全局配置里有个参数:navigationStyle(导航栏样式),default=默认样式,custom=自定义样式。

"window": { "navigationStyle": "custom" }

让我们看看隐藏后的效果:

微信小程序自定义navigationBar顶部导航栏适配所有

可以看到原生的navigationBar已经消失了,剩下孤零零的胶囊按钮,胶囊按钮是无法隐藏的。

二、准备工作

1.获取胶囊按钮的布局位置信息

我们用wx.getMenuButtonBoundingClientRect() 【官方文档】 获取胶囊按钮的布局位置信息,坐标信息以屏幕左上角为原点:

const menuButtonInfo = wx.getMenuButtonBoundingClientRect();

width height top right bottom left
宽度   高度   上边界坐标   右边界坐标   下边界坐标   左边界坐标  

下面是官方给的示意图,方便大家理解几个坐标。

微信小程序自定义navigationBar顶部导航栏适配所有

2.获取系统信息

用wx.getSystemInfoSync() 【官方文档】 获取系统信息,里面有个参数:statusBarHeight(状态栏高度),是我们后面计算整个导航栏的高度需要用到的。

const systemInfo = wx.getSystemInfoSync();

三、计算公式

我们先要知道导航栏高度是怎么组成的, 计算公式: 导航栏高度 = 状态栏到胶囊的间距(胶囊距上距离-状态栏高度) * 2 + 胶囊高度 + 状态栏高度 。

实例 【源码下载

自定义导航栏会应用到多个、甚至全部页面,所以封装成组件,方便调用;下面是我写的一个简单例子:

app.js

App({ onLaunch: function(options) { const that = this; // 获取系统信息 const systemInfo = wx.getSystemInfoSync(); // 胶囊按钮位置信息 const menuButtonInfo = wx.getMenuButtonBoundingClientRect(); // 导航栏高度 = 状态栏到胶囊的间距(胶囊距上距离-状态栏高度) * 2 + 胶囊高度 + 状态栏高度 that.globalData.navBarHeight = (menuButtonInfo.top - systemInfo.statusBarHeight) * 2 + menuButtonInfo.height + systemInfo.statusBarHeight; that.globalData.menuRight = systemInfo.screenWidth - menuButtonInfo.right; that.globalData.menuBotton = menuButtonInfo.top - systemInfo.statusBarHeight; that.globalData.menuHeight = menuButtonInfo.height; }, // 数据都是根据当前机型进行计算,这样的方式兼容大部分机器 globalData: { navBarHeight: 0, // 导航栏高度 menuRight: 0, // 胶囊距右方间距(方保持左、右间距一致) menuBotton: 0, // 胶囊距底部间距(保持底部间距一致) menuHeight: 0, // 胶囊高度(自定义内容可与胶囊高度保证一致) } })

app.json

{ "pages": [ "pages/index/index" ], "window": { "navigationStyle": "custom" }, "sitemapLocation": "sitemap.json" }

下面为组件代码: /components/navigation-bar/navigation-bar.wxml

<!-- 自定义顶部栏 --> <view> <input placeholder="输入关键词!"></input> </view> <!-- 内容区域: 自定义顶部栏用的fixed定位,会遮盖到下面内容,注意设置好间距 --> <view></view>

/components/navigation-bar/navigation-bar.json

{ "component": true }

/components/navigation-bar/navigation-bar.js

const app = getApp() Component({ properties: { // defaultData(父页面传递的数据-就是引用组件的页面) defaultData: { type: Object, value: { title: "我是默认标题" }, observer: function(newVal, oldVal) {} } }, data: { navBarHeight: app.globalData.navBarHeight, menuRight: app.globalData.menuRight, menuBotton: app.globalData.menuBotton, menuHeight: app.globalData.menuHeight, }, attached: function() {}, methods: {} })

/components/navigation-bar/navigation-bar.wxss

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/d7986f5ba908bb216dc5a63e8eb1ab00.html