都2023了,自定義頂部導航應該不是什么新鮮事了,這里只是簡單記錄下
微信自己也提供了自定義頂部導航navigation-bar,大概看了下,可配置的也不少,所以看需求了,如果簡單可以采用微信提供的,老規(guī)矩,先看效果
1、補充幾個前置知識
- 狀態(tài)欄高度(getSystemInfoSync),就是手機頂部網(wǎng)絡那塊的高度
- 膠囊位置信息(getMenuButtonBoundingClientRect),右邊那個像膠囊一樣的東西,通過它我們可以知道高度,計算出右邊的padding
綜上可知,整導航欄的高度其實是 1 所在區(qū)域 = 狀態(tài)欄高度 + 膠囊高度 + ( 膠囊距離頂部 - 狀態(tài)欄高度 ) * 2
因為,膠囊和狀態(tài)欄之間還有一定間隙,所以完整的高度需要 膠囊距離頂部 - 狀態(tài)欄高度
2、實現(xiàn)
首先需要知道上面說的那幾個位置信息,思路分析
- 通常這些信息在小程序啟動的時候獲取一次就行了,所以我們需要做兩手準備,如果全局里面沒有,則導航組件再自己獲取一次
- 如果沒有獲取到,應該有默認值(這時候樣式肯定有不好看,不過沒辦法~)
- 頂部一般是定位固定的,所以用了導航組件后,應該有一個盒子用于占位補充定位導致塌陷的高度
3、完整代碼如下
js如下
// component/navBar/navBar.js
const app = getApp()
Component({
/**
* 組件的屬性列表
*/
properties: {
// 標題
title: {
type: String,
value: ''
},
// 是否需要返回
hasBack: {
type: Boolean,
value: false
},
// 背景色
bgc: {
type: String,
value: 'linear-gradient(to top, #96fbc4 0%, #f9f586 100%)'
},
// 是否固定
isFixed: {
type: Boolean,
value: true
}
},
/**
* 組件的初始數(shù)據(jù)
*/
data: {
navInfo: {
paddingLeft: 0,
paddingTop: 0,
navHeight: 0
},
},
/**
* 生命周期鉤子
* **/
lifetimes: {
created() {
const { getSystemInfoSync, menuInfo} = app.globalData
if(!Object.keys(getSystemInfoSync).length || !Object.keys(menuInfo).length) {
console.warn('沒有膠囊位置信息,重新獲取中')
this.customNavBarInfo()
}
},
attached() {
// 計算導航高度信息
this.getNavBarInfo()
}
},
/**
* 組件的方法列表
*/
methods: {
/**
* 計算導航高度信息
* **/
getNavBarInfo() {
// 防止沒有獲取到位置信息
let navInfo = {
paddingLeft: 7, // 默認膠囊距離屏幕右邊的距離
paddingTop: 20,// 默認
navHeight: 44 // 默認導航欄高度
}
if(Object.keys(app.globalData.menuInfo).length && Object.keys(app.globalData.getSystemInfoSync).length) {
const { top,height,right,width } = app.globalData.menuInfo
const { statusBarHeight,windowWidth } = app.globalData.getSystemInfoSync
navInfo = {
paddingLeft: windowWidth - right,
paddingTop: statusBarHeight,
navHeight: height + ( top - statusBarHeight ) * 2,
menuWidth: width
}
}
this.setData({
navInfo
})
},
/**
* 獲取膠囊位置信息
* **/
customNavBarInfo() {
app.globalData.menuInfo = wx.getMenuButtonBoundingClientRect()
app.globalData.getSystemInfoSync = wx.getSystemInfoSync()
},
}
})
css如下文章來源:http://www.zghlxwxcb.cn/news/detail-617287.html
.nav{
display: flex;
align-items: center;
}
// 這是筆者寫一個寬度,需要根據(jù)自己情況調整
.left{
width: 80rpx;
}
.custom-nav{
z-index: 999;
top: 0;
right: 0;
left: 0;
}
通常在app.js里面提前獲取一次文章來源地址http://www.zghlxwxcb.cn/news/detail-617287.html
App({
onLaunch() {
this.globalData.menuInfo = wx.getMenuButtonBoundingClientRect() || {}
this.globalData.getSystemInfoSync = wx.getSystemInfoSync() || {}
},
globalData: {
// 完整膠囊信息
menuInfo: {},
// 完整系統(tǒng)信息
getSystemInfoSync: {},
}
})
到了這里,關于微信原生小程序自定義頂部導航的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!