1、app.jsonでカスタムナビゲーションを有効化
"window": {
"navigationStyle": "custom"
},
2、app.jsでシステム情報を取得し、グローバル変数に保存
App({
onLaunch() {
const instance = this;
// システム情報の取得
const deviceInfo = wx.getSystemInfoSync();
// カプセルボタンの位置情報
const capsuleInfo = wx.getMenuButtonBoundingClientRect();
// ナビゲーションバー高さ = ステータスバー + 44
instance.globalData.navHeight = deviceInfo.statusBarHeight + 44;
instance.globalData.capsuleRight = deviceInfo.screenWidth - capsuleInfo.right;
instance.globalData.capsuleBottom = capsuleInfo.top - deviceInfo.statusBarHeight;
instance.globalData.capsuleHeight = capsuleInfo.height;
console.log('カプセル下マージン', instance.globalData.capsuleBottom);
},
// 各デバイスに応じた動的計算で高い互換性を実現
globalData: {
navHeight: 0, // ナビゲーションバー高さ
capsuleRight: 0, // カプセル右マージン
capsuleBottom: 0, // カプセル下マージン
capsuleHeight: 0, // カプセル高さ
},
})
3、コンポーネントの宣言
WXML
<!-- カスタムヘッダー -->
<view class="custom-header" style="height:{{navHeight}}px;background:url({{bgImage}}) no-repeat;background-size: cover;">
<view class="header-content" style="height:{{capsuleHeight}}px; min-height:{{capsuleHeight}}px; line-height:{{capsuleHeight}}px; bottom:{{capsuleBottom}}px;">
<image wx:if="{{config.showBack}}" bind:tap="navigateBack" style="margin-left: {{capsuleRight}}px;" class="back-icon" src="/assets/icons/arrow-back.svg" mode=""/>
<view class="page-title" style="color: {{config.textColor}};">{{config.pageTitle}}</view>
</view>
</view>
<!--
コンテンツエリア:
fixed定位によりコンテンツが隠れるため、適切なマージンを設定
-->
<!-- <view class="main-content" style="margin-top:{{navHeight}}px;"></view> -->
JS
const globalApp = getApp()
Component({
properties: {
config: {
type: Object,
value: {
pageTitle: "デフォルトタイトル",
textColor: '#333',
showBack: false,
},
observer: function (newVal, oldVal) {}
},
bgImage: {
type: String,
value: '',
observer: function (newVal, oldVal) {
this.setData({
// プロパティ変更時の処理
});
}
}
},
data: {
navHeight: globalApp.globalData.navHeight,
capsuleRight: globalApp.globalData.capsuleRight,
capsuleBottom: globalApp.globalData.capsuleBottom,
capsuleHeight: globalApp.globalData.capsuleHeight,
},
created:function(){
wx.loadFontFace({
family: 'Noto Sans JP',
global: true,
source: 'url("https://fonts.gstatic.com/s/notosansjp/v32/-F6pfjtqLzI2JPCgQBnw7HFowQoqk.woff2")',
success(res) {
console.log('フォント読み込み成功', res.status)
},
fail: function (res) {
console.log('フォント読み込み失敗', res.status)
}
});
},
attached: function () {},
methods: {
navigateBack: function() {
wx.navigateBack({
delta: 1
});
}
}
})
WXSS
.custom-header {
position: fixed;
z-index: 9999;
width: 100%;
top: 0;
}
.header-content{
width: 100%;
position: absolute;
display: flex;
align-items: center;
}
.page-title{
flex: 1;
text-align: center;
font-family: Noto Sans JP;
font-weight: 600;
font-size: 32rpx;
}
.back-icon{
width: 24rpx;
height: 24rpx;
float: left;
}
JSON
{
"component": true,
"usingComponents": {}
}