在微信小程序开发过程中,经常会有特殊需求自定义导航栏,本篇博客介绍如何自定义导航栏组件,可在多页面使用
1、在 onLaunch 方法中获取系统导航栏布局信息存入全局变量
App({ //设置导航栏 //获取菜单按钮的布局位置信息 let menuButtonObject = wx.getMenuButtonBoundingClientRect(); //获取系统信息 wx.getSystemInfo({ success: res => { //状态栏的高度 let statusBarHeight = res.statusBarHeight, //胶囊按钮与顶部的距离 navTop = menuButtonObject.top, navHeight = statusBarHeight + menuButtonObject.height + (menuButtonObject.top - statusBarHeight) * 2; this.globalData.navHeight = navHeight;//导航栏高度 this.globalData.navTop = navTop;//胶囊按钮与顶部的距离 this.globalData.jnheight = menuButtonObject.height;//胶囊的高度 this.globalData.jnwidth = menuButtonObject.width;//胶囊的宽度 }, fail(err) { console.log(err); } }); //设置全局对象 globalData: { navHeight: 0, navTop: 0, jnheight: 0, jnwidth: 0, } })
2、自定义 navbar 组件
2.1、navbar.wxml代码
{{pageName}}
2.2、navbar.js代码
const App = getApp(); Component({ // 组件的属性列表 properties: { pageName: String, //中间的title showNav: { //判断是否显示左上角的按钮 type: Boolean, value: true }, showHome: { //判断是否显示左上角的home按钮 type: Boolean, value: true } }, // 组件的初始数据 data: { showNav: true, //判断是否显示左上角的home按钮 showHome: true, //判断是否显示左上角的按钮 }, lifetimes: { // 生命周期函数,可以为函数,或一个在methods段中定义的方法名 attached: function() { this.setData({ navHeight: App.globalData.navHeight, //导航栏高度 navTop: App.globalData.navTop, //胶囊按钮与顶部的距离 jnheight: App.globalData.jnheight, //胶囊高度 jnwidth: App.globalData.jnwidth //胶囊宽度 }) } }, // 组件的方法列表 methods: { //回退 navBack: function() { wx.navigateBack() }, //回主页 navHome: function() { wx.switchTab({ url: '/pages/home/home' }) }, } })
2.3、navbar.wxss代码
.navbar { width: 100%; overflow: hidden; position: sticky; top: 0; left: 0; z-index: 10; flex-shrink: 0; background: #fff; } .navbar_left { display: -webkit-flex; display: flex; -webkit-box-align: center; -ms-flex-align: center; -webkit-align-items: center; align-items: center; position: absolute; left: 10px; z-index: 11; line-height: 1; border: 1rpx solid #f0f0f0; border-radius: 40rpx; overflow: hidden; background: rgba(255, 255, 255, 0.6); } .navbar_left view { width: 50%; display: flex; align-items: center; justify-content: center; } .nav_line { border-left: 1rpx solid #f0f0f0; } .navbar_title { width: 100%; box-sizing: border-box; padding-left: 115px; padding-right: 115px; height: 32px; line-height: 32px; text-align: center; position: absolute; left: 0; z-index: 10; color: #333; font-size: 16px; font-weight: bold; text-overflow: ellipsis; overflow: hidden; white-space: nowrap; }
3、使用 navbar 组件
.json文件中设置自定义导航栏,并引入 navbar 组件
{ "navigationStyle":"custom", "usingComponents":{ "navbar":"/components/navbar/navbar" } }
.wxml文件中使用 navbar 组件
End!