多样化自定义小程序导航栏
发表时间:2021-1-5
发布人:葵宇科技
浏览次数:40
效果如下随意变换:(随便拿了星巴克小程序图,侵删)
navbar-for-wxapp
一、如何实现
1. index.js
/*
* @Author: mtonhuang
* @Feature: 小程序自定义导航栏组件
*/
Component({
properties: {
titleText: { //导航栏文字
type: String,
value: '导航栏'
},
backgroundImg: { //背景图片路径
type: String,
value: ''
},
backIcon: { //返回按钮
type: String,
value: ''
},
homeIcon: { //房子按钮
type: String,
value: ''
}
},
attached: function(){
const self = this;
self.getSysmInfo();
},
data: {
},
methods: {
getSysmInfo: function() {
const self = this;
wx.getSystemInfo({
success: function(res) {
let isIos = res.system.indexOf('iOS') > -1;
let status = res.statusBarHeight;
self.setData({
navHeight: isIos ? 44 : 48,
status: status
})
}
})
},
back: function(){
this.triggerEvent('back')
},
home: function() {
this.triggerEvent('home');
}
}
})
复制代码
2. index.wxml
<view class="nav" style="height: {{status + navHeight}}px">
<view class="index-banner" wx:if="{{backgroundImg}}">
<image class="index-banner__cover" mode="scaleToFill" src="{{backgroundImg}}"></image>
</view>
<view class="status" style="height: {{status}}px;"></view>
<view class="navbar" style="height:{{navHeight}}px;">
<view class="capsule" style="{{backIcon ? '' : 'width: 152rpx;margin-left: 24rpx'}}">
<view class="back-icon" wx:if="{{backIcon}}" bindtap="back">
<image class="imag_back" src="{{backIcon}}"></image>
</view>
<view class="home-icon" wx:if="{{homeIcon}}" bindtap="home" style="{{backIcon ? '' : 'left: 84.2rpx'}}">
<image class="imag_home" src="{{homeIcon}}"></image>
</view>
</view>
<view class="nav-title" wx:if="{{titleText}}">
<text>{{titleText}}</text>
</view>
</view>
</view>
复制代码
二、如何使用1. 【必填】index.json
{
"navigationStyle": "custom", //自定义导航栏,必填
"usingComponents": {
"nav-bar": "../../components/navBar/navBar" //引入我们的组件
}
}
复制代码
2. 【必填】index.wxml
- 给页面的最大父级 padding-top
- 引入组件,名称为 index.json 中自定义的组件名称 nav-bar
- 根据自己需要配置 背景图,回退 icon,小房子按钮,标题文字等
<view class="page" style="padding-top: {{height + status}}px">
<nav-bar
bindback="back"
bindhome="home"
backIcon="../../assets/img/svg/back.svg"
homeIcon="../../assets/img/svg/home.svg"
titleText="这是自定义导航栏"
backgroundImg="test.png"
backIcon="../../assets/img/svg/back_default.svg">
</nav-bar>
</view>
复制代码
3. 【必填】根据不同机型,计算出 height 与 status 的值
onLoad() {
let that = this;
wx.getSystemInfo({
success: function(res) {
let isIos = res.system.indexOf('iOS') > -1;
let status = res.statusBarHeight;
that.setData({
height: isIos ? 44 : 48,
status: status
})
}
})
}
复制代码
4. 【选填】事件 back 或者 home
// 根据业务需求
back: function () {
wx.reLaunch({
url: '../index/index'
})
}
home: function () {
wx.reLaunch({
url: '../index/index'
})
}
复制代码
5.【选填】读者也可以自定义字体颜色等,写法就不再赘述
Contributor
- mtonhuang
当然,喜欢的话,请不要吝啬您的start for my github blog,Thanks?(?ω?)?