小程式開發-自定義導航欄元件
阿新 • • 發佈:2020-09-07
上一篇文章講到了小程式設定全屏,隱藏導航欄的方式。
主要是配置自定義導航欄"navigationStyle": "custom"
這篇文章嘗試自定義導航欄
1. 首先,我們要獲取狀態列的高度,以及膠囊的位置
可以通過getSystemInfo
方法
//獲取選單按鈕(右上角膠囊按鈕)的佈局位置資訊 let menuButtonObject = wx.getMenuButtonBoundingClientRect(); //獲取系統資訊 wx.getSystemInfo({ success: res => { //狀態列的高度 let statusBarHeight = res.statusBarHeight, //膠囊按鈕與頂部的距離 navTop = menuButtonObject.top, navHeight = statusBarHeight + menuButtonObject.height + (menuButtonObject.top - statusBarHeight) * 2; this.globalData.statusBarHeight = statusBarHeight ;//狀態列高度 this.globalData.navHeight = navHeight;//導航欄高度 this.globalData.navTop = navTop;//膠囊按鈕與頂部的距離 this.globalData.jnHeight = menuButtonObject.height;//膠囊的高度 this.globalData.jnWidth = menuButtonObject.width;//膠囊的寬度 }, fail(err) { console.log(err); }
2. 自定義導航欄 navigationBar
navigationBar.js
程式碼
const app = getApp() Component({ properties: { title: { type: String, value: 'weiChat' }, back: { type: Boolean, value: false }, home: { type: Boolean, value: false } }, data: { navigationBarHeight: app.globalData.navHeight statusBarHeight: app.globalData.statusBarHeight }, methods: { backHome: function () { let pages = getCurrentPages() wx.navigateBack({ delta: pages.length }) }, back: function () { wx.navigateBack({ delta: 1 }) }, loading: { type: Boolean, value: false } } })
navigationBar.wxss
程式碼
白色導航欄,
.navbar { width: 100%; background-color: #fff; position: fixed; top: 0; left: 0; z-index: 999; } .title-container { height: 40px; display: flex; align-items: center; position: relative; } .capsule { margin-left: 10px; height: 30px; background: rgba(255, 255, 255, 0.6); border: 1px solid #eee; border-radius: 16px; display: flex; align-items: center; } .capsule > view { width: 45px; height: 60%; position: relative; } .capsule > view:nth-child(2) { border-left: 1px solid #eee; } .capsule image { width: 20px; height: 20px; position: absolute; left: 50%; top: 50%; transform: translate(-10px,-10px); } .title { position: absolute; top: 6px; left: 104px; right: 104px; height: 30px; line-height: 30px; font-size: 18px; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .navBar-loader { height: 18px; width: 18px; display: inline-block; margin-right: 4px; vertical-align: middle; }
navigationBar.wxml
程式碼
<view class="navbar" style="{{'height: ' + navigationBarHeight}}">
<view style="{{'height: ' + statusBarHeight}}"></view>
<view class='title-container'>
<view class='capsule' wx:if="{{ back || home }}">
<view bindtap='back' wx:if="{{back}}">
<image src='/images/back.png'></image>
</view>
<view bindtap='backHome' wx:if="{{home}}">
<image src='/images/home_top.png'></image>
</view>
</view>
<view class='title'><view wx:if="{{loading}}" class="navBar-loader"><view class="inner"></view></view>{{text}}</view>
</view>
</view>
<view style="{{'height: ' + navigationBarHeight}};background: white;"></view>
3. 使用
<navigationBar title="{{title}}" loading="{{true}}" home="{{true}}" back="{{true}}"></navigationBar>