目录

1. 前言2. 效果展示3.文件目录结构4.如何使用5. 实现代码6. 原理分析

1. 前言

小程序开发中,有时我们不需要自带的导航栏,那就需要自己写一个这样的导航栏。

2. 效果展示

3.文件目录结构

├── root

│ ├── components

│ │ └── navbar

│ │ ├── index.js

│ │ ├── index.wxml

│ │ ├── index.json

│ │ ├── index.wxss

│ ├──pages

│ │ ├── index.js

│ │ ├── index.wxml

│ │ ├── index.json

│ │ ├── index.wxss

└──── app.js

4.如何使用

pages/index

Page({

data: {

navbarData: {

showCapsule: 1, //是否显示头部左上角小房子 1显示 0 不显示

showBack: 1, //是否显示返回 1显示 0不显示

// showColor: 0, //navbar背景颜色 1展示 0不展示

// navigationBarColor: 'yellow',

bgTransparent: true, // 时候否透明

iconColor: 'black',

titleColor: 'black',

title: '首页'

},

},

})

5. 实现代码

需要现在app.js启动的时候获取一些信息 app.js

// app.js

App({

onLaunch() {

const { statusBarHeight, titleBarHeight } = getStatusBarHeight()

console.log(statusBarHeight, titleBarHeight)

this.globalData.statusBarHeight = statusBarHeight;

this.globalData.titleBarHeight = titleBarHeight;

},

globalData: {

statusBarHeight: "",

titleBarHeight: ""

}

})

function getStatusBarHeight() {

let res = wx.getSystemInfoSync()

let customTitleBarHeight;

try {

const menuInfo = wx.getMenuButtonBoundingClientRect();

if (equalVersion(res.version, "7.0.3")) {

customTitleBarHeight =

menuInfo.height + (menuInfo.top - res.statusBarHeight) * 2;

} else {

customTitleBarHeight = menuInfo.height + menuInfo.top * 2;

}

} catch (e) {

customTitleBarHeight = 48;

}

if (res.model.indexOf("iPhone") !== -1) {

customTitleBarHeight = 44;

}

return {

statusBarHeight: res.statusBarHeight,

titleBarHeight: customTitleBarHeight,

}

};

function equalVersion(curV, reqV) {

let arr1 = curV.split(".");

let arr2 = reqV.split(".");

let maxL = Math.max(arr1.length, arr2.length);

let pos = 0;

let diff = 0;

while (pos < maxL) {

diff = parseInt(arr1[pos]) - parseInt(arr2[pos]);

console.log(diff, parseInt(arr1[pos]), parseInt(arr2[pos]));

if (diff != 0) {

break;

}

pos++;

}

if (diff > 0 || diff == 0) {

//新版本、稳定版

return 1;

} else {

// 旧版本

return 0;

}

}

下面是组件代码 component/navbar.js

/**

* 自定义头部

*/

const app = getApp()

// 版本号比较函数

function compareVersion(v1, v2) {

v1 = v1.split('.')

v2 = v2.split('.')

const len = Math.max(v1.length, v2.length)

while (v1.length < len) {

v1.push('0')

}

while (v2.length < len) {

v2.push('0')

}

for (let i = 0; i < len; i++) {

const num1 = parseInt(v1[i])

const num2 = parseInt(v2[i])

if (num1 > num2) {

return 1

} else if (num1 < num2) {

return -1

}

}

return 0

}

Component({

properties: {

navbarData: { //navbarData 由父页面传递的数据,变量名字自命名

type: Object,

value: {},

observer: function (newVal, oldVal, changedPath) {

if (newVal == null && typeof (oldVal) == 'object') {

try {

var _o = {};

var defaultData = {

statusBarHeight: '',

titleBarHeight: '',

navbarData: {

showCapsule: 1, //是否显示左上角小房子 1显示 0 不显示

showBack: 1, //是否显示返回 1显示 0不显示

showColor: 1, //navbar背景颜色 1蓝色 0白色

navigationBarColor: '#ffffff',

bgTransparent: false, // true 背景为透明 false 不透明(下面两个属性也不生效)

iconColor: 'black', // white 左侧icon颜色

titleColor: '#000000' // 可以指定title具体色值

}

}

_o['navibarData'] = defaultData['navbarData']

this.setData(_o);

} catch (e) {

}

} else {

// var data = this.data;

var data = {};

var path = 'navibarData';

Object.keys(newVal).forEach(key => {

data[`${path}.${key}`] = newVal[key];

})

this.setData(data);

}

}

}

},

data: {

statusBarHeight: '',

titleBarHeight: '',

showNavbar: '',

menuButtonInfo: {},

navibarData: {

showCapsule: 0, //是否显示左上角小房子

showBack: 1, //是否显示返回

showColor: 1, //navbar背景颜色,

navigationBarColor: '#ffffff',

bgTransparent: false, // true 背景为透明 false 不透明(下面两个属性也不生效)

iconColor: 'black', // white 左侧icon颜色

titleColor: '#000000' // 可以指定title具体色值

}

},

attached: function () {

if (wx.getSystemInfoSync().platform.toLowerCase().indexOf('devtools') != -1) {

this.setData({

showNavbar: true

});

} else {

// 获取版本号

const version = wx.getSystemInfoSync().version

if (compareVersion(version, '7.0.0') >= 0) {

// 版本号大于7.0.0时,显示自定义头部

this.setData({

showNavbar: true

})

} else {

// // 版本号低于7.0.0时,隐藏自定义头部

this.setData({

showNavbar: false

})

}

}

this.setData({

statusBarHeight: app.globalData.statusBarHeight,

titleBarHeight: app.globalData.titleBarHeight

});

//获取右上角胶囊的大小,为显示自定义icon做准备

this.setData({

menuButtonInfo: wx.getMenuButtonBoundingClientRect()

});

},

ready() {

try {

const currentPages = getCurrentPages()

const _o1 = {}

//无论如何返回按钮出现的规则不变

if (currentPages.length > 1) {

_o1.showBack = true;

} else {

_o1.showBack = false;

}

this.setData({

navibarData: {

...this.data.navibarData,

..._o1

}

})

} catch (e) {

}

},

methods: {

//返回到首页

_backhome(e) {

wx.switchTab({

url: '/pages/home/homepage',

});

},

_backlast(e) {

wx.navigateBack();

},

},

})

component/navbar.wxml