背景:
小程序頂部導航欄那里的樣式和功能都是小程序自帶的,當我們在pages.json里的pages里新加一條頁面配置時,會自動生成一個帶頂部導航欄的空白頁面,當然也可以再配置里"navigationBarTitleText","navigationBarTextStyle","navigationBarBackgroundColor",來改變導航欄標題字體,標題字體顏色,導航欄背景顏色,其實上面那些配置一般的應用場景下夠用了, 但是有時候產品就偏偏不想用他的默認樣式, 想在那里放張背景圖, 放個輸入框, 放個按鈕啥的,這時候就需要自定義導航條了
實現:
-
pages.json里配置navigationStyle為custom
{ "path": "pages/index/index", "pageOrientation": "landscape", "style": { "navigationStyle":"custom", } },
- 如上配置好后即可實現自定義導航欄,不過直接寫的話會有機型樣式的差異, 如iPhoneX等機型的劉海屏會遮住部分內容,處理辦法是獲取導航欄信息,根據小程序右上角的膠囊定位, 代碼如下
onLaunch: function() {// 獲取系統信息 const systemInfo = uni.getSystemInfoSync(); // 獲取膠囊按鈕的位置 const menuButtonInfo = uni.getMenuButtonBoundingClientRect(); // 導航欄高度 = 狀態欄到膠囊的間距( 膠囊距上距離 - 狀態欄高度 )*2 + 膠囊高度 + 狀態欄高度 this.globalData.navBarHeight = (menuButtonInfo.top - systemInfo.statusBarHeight) * 2 + menuButtonInfo .height + systemInfo.statusBarHeight; this.globalData.menuRight = systemInfo.screenWidth - menuButtonInfo.right; this.globalData.menuBotton = menuButtonInfo.top - systemInfo.statusBarHeight; this.globalData.menuHeight = menuButtonInfo.height;
}, globalData: { navBarHeight: </span>0, <span style="color: #008000;">//</span><span style="color: #008000;"> 導航欄高度</span> menuRight: 0, <span style="color: #008000;">//</span><span style="color: #008000;"> 膠囊距右方間距(方保持左、右間距一致)</span> menuBotton: 0, <span style="color: #008000;">//</span><span style="color: #008000;"> 膠囊距底部間距(保持底部間距一致)</span> menuHeight: 0, <span style="color: #008000;">//</span><span style="color: #008000;"> 膠囊高度(自定義內容可與膠囊高度保證一致)</span> },</pre>
這樣就獲取到了所需信息並存到了globalData全局變量里
在頁面或組件里用到這些信息
export default { data() { return { // 機型頂部適配 navBarHeight: getApp().globalData.navBarHeight, menuRight: getApp().globalData.menuRight, menuBotton: getApp().globalData.menuBotton, menuHeight: getApp().globalData.menuHeight, }}</span><span style="color: #000000;"> }</span></pre>
思路如上, 部分樣式代碼沒貼上去自行添加即可