在自定義小程式導航欄時,右上角的膠囊(MenuButton)在不同機型測驗,會發現很難適配,
實測中 不同的手機,膠囊高度不一樣、狀態欄高度不一樣,與模擬器顯示的情況是不一樣的,
完全需要根據手機,動態的計算高度,
先看一些小程式頂部導航欄適配的情況

圖一 某團 圖二 某乎 圖三 某東 圖四 某拉
上圖適配做的最好的是某東,但仔細看仍會有一點錯位,但輸入框的顏色,淡化了這種不和諧感,
為解決這個問題就要搞清楚原理

這是在沒有設定自定義時的原生導航欄,我們發現整體的高度就是 (狀態欄高度 + 導航欄高度)
而狀態欄高度可以通過 wx.getSystemInfo()獲取,現在就只用解決導航欄高度了
觀察發現,膠囊頂部高度距導航欄頂部高度的高度差 和 膠囊底部高度距導航欄底部高度的高度差,是一樣的
也就是說 導航欄高度 = 膠囊高度 +(高度差)x 2
而膠囊資訊可以通過 wx.getMenuButtonBoundingClientRect() 獲取,現在就只用解決高度差了
wx.getMenuButtonBoundingClientRect() 中也回傳了膠囊頂部距螢屏頂部距離的資訊(top)
所以知 高度差 = 膠囊頂部距螢屏頂部距離 - 狀態欄高度
用這兩個API 我們可以得到如下的資料

導航欄整體高度 偽呆🐎
menu = wx.getMenuButtonBoundingClientRect()
system = wx.getSystemInfo
導航欄高度 = menu.statusBarHeight + menu.height + (menu.top - menu.statusBarHeight) * 2
到此我們就完美解決了導航欄高度的問題
而導航欄內容就是
內容標簽的view高度等于menu.height并且垂直居中
效果

真機效果

最終效果

講完了 上呆🐎
注: 一般需將自定義導航欄單獨出來為組件
app.js 呆🐎
//app.js
App({
globalData: {},
onLaunch: function() {
//獲取系統資訊
wx.getSystemInfo({
success: res => {
this.system = res
}
})
//獲取膠囊資訊
this.menu = wx.getMenuButtonBoundingClientRect()
//列印資料
console.log('系統資訊', this.system)
console.log('膠囊資訊', this.menu)
}
})
組件.js 呆🐎
//獲取應用實體
const app = getApp()
Component({
/**
* 組件的屬性串列
*/
properties: {
//導航欄顏色
navColor: {
type: String,
value: '#fff'
}
},
/**
* 組件的初始資料
*/
data: {
s: app.system.statusBarHeight, //狀態欄高度
n: (app.menu.top - app.system.statusBarHeight) * 2 + app.menu.height, //導航欄高度
h: app.menu.height //膠囊高度
}
})
組件.wxml 呆🐎
<cover-view class='nav_box' style='background:{{navColor}}'>
<cover-view style='height:{{s}}px' />
<cover-view class='navBar' style='height:{{n}}px'>
<cover-view class='content' style='height:{{h}}px'>
<!-- 導航自定義內容 -->
<!-- 1. 插槽 可在使用頁面插入所需內容 -->
<slot></slot>
<!-- 2. 選擇渲染 可在js頁面 設定渲染type屬性 不同場景傳不同值 -->
<block wx:if='{{type == 0}}'>
導航一
</block>
<block wx:if='{{type == 1}}'>
導航二
</block>
<block wx:else>
導航三
</block>
</cover-view>
</cover-view>
</cover-view>
<view style='height:{{s+n}}px' /> <!-- 注:占位用 -->
組件. wxss 呆🐎
.nav_box {
position: fixed;
width: 100%;
font-size: 15px;
z-index: 999;
}
.navBar {
display: flex;
align-items: center;
padding: 0 10px;
}
.content {
width: 100%;
display: flex;
align-items: center;
background: green;
}
組件使用頁面.json 呆🐎
{
"navigationStyle": "custom", //設定自定義導航
"usingComponents": {
"navBar": "../../組件/navBar/navBar" //自己的路徑
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/182882.html
標籤:python
下一篇:2020ccpc秦皇島總結
