自定義微信小程序標題欄

現在各大應用都有小程序了,今日頭條,百度App,支付寶等,其實我們使用的比較多的還是微信小程序,作為前端程序員要把微信小程序加入到自己的技術棧裡面來,各大公司都要求會微信小程序的開發,現在我也挺看好頭條的小程序。

微信小程序的開發非常的簡單,開發文檔比較完善,社區也比較活躍,對程序員比較友好,微信小程序開發你主要懂HTML,CSS,JavaScript的基礎知識就可以開發,開發的過程中主要解決用戶授權登錄,還有分享邏輯等基本就沒有什麼太大的難題。

年初老闆加需求,小程序做一個引導頁,這要求太奇葩了,沒有辦法只能硬著頭皮去完成,因為我原來的代碼都是使用小程序默認的標題欄,引導頁的banner圖肯定有要做成全屏的要不然很難看。微信小程序沒有對單個頁面設置全屏,只有對所有的頁面設置全屏的。

//app.json
"window":{
"navigationStyle":"custom"
}

這樣子設置我所有的代碼都要改了,我其他的頁面需要標題欄那就要自己添加標題欄上去啊!老闆這是不讓我閒下來啊!

我們知道不同的手機手機頂部的佔用高度是不同的,特別是現在流行的劉海機,iPhone X,iPhone XR 等機的頂部有跟老機型iPhone 8的完全不同,這個適配怎麼做,尺寸是多少,

微信小程序的右上角還有一個膠囊,這個膠囊還是無法隱藏的。

在安卓,IOS app有API 獲取這個高度,微信也是通過這個高度來定小程序標題欄的高度,關鍵是微信有沒有暴露這個API給小程序。還真的有:

// app.js
App({
onLaunch:function(e){
const respx = wx.getSystemInfoSync();
console.log(respx.statusBarHeight) //這個就是手機頂部的高度單位是px
}
})

解決了頂部那塊接下來就是解決小程序膠囊按鈕了,測試了多臺手機發現44px高度比較好,只能說是比較理想了並不是特別的完美;

this.globalData.statusBarHeight = respx.statusBarHeight+44;

這個高度存為全局變量了,作為標題欄的高度。

下面是我寫的導航template,其他的頁面直接引用就行。

// header.wxml
<template>
\t<view>
\t\t<navigator><text>/<navigator>
\t\t<view><text>{{barTitle?barTitle:'正在加載'}}/<text>/<view>
\t/<view>
/<template>
<template>
\t<view>
\t\t<navigator><text>/<navigator>
\t/<view>
/<template>

//app.wxss
.nav-header-title{
\twidth: 100%;
\tbackground: #0CCCBB;
\tposition: fixed;
\tleft: 0;
\tright: 0;
\tz-index: 10000;
\toverflow: hidden;
}
.nav-header-title .title{
\twidth: 100%;
\theight: 44px;
\tline-height: 44px;
\ttext-align: center;
\tcolor: #FFFFFF;
\tfont-size:32rpx;
}
.nav-header-title .title .tit{
\tdisplay: block;
\twidth: 100%;
\theight: 100%;
\tbox-sizing: border-box;
\tpadding: 0 150rpx;
\tdisplay: -webkit-box !important;
\t word-break: break-all;
\t text-overflow: ellipsis;
\t overflow: hidden;
\t -webkit-box-orient: vertical;
\t -webkit-line-clamp:1;
}
.nav-header-title .nav-back{
\tposition: absolute;
\theight: 44px;
\tleft: 0;
\tbox-sizing: border-box;
}
.nav-header-title .nav-back .icon{
\tpadding: 20rpx;
\tposition: absolute;
\ttop: 50%;
\ttransform: translateY(-50%);
\tcolor: #FFFFFF;
\tfont-size:32rpx;
}
.navigator-back{
\tposition: fixed;
\tleft: 10px;
\twidth: 30px;
\theight: 30px;

\tbackground: rgba(255,255,255,0.5);
\tline-height: 30px;
\ttext-align: center;
\tborder-radius: 50%;
}
.navigator-back navigator text{
\tcolor: #14CEBC;
\tfont-size:32rpx;
}

然後其他的頁面想使用的直接是

// index.wxml
<import>
<template>
<view>
/<view>
//index.js
onLoad:function(options){
this.setData({
showBack:true,
barTitle:某某公司,
barHeight:app.globalData.statusBarheight
})
}

上面的代碼只有稍修改就可以使用,如果大家還有更好的方法可以在下方評論。


分享到:


相關文章: