微信小程式自定義tabbar
原文地址:http://www.wxapp-union.com/article-1405-1.html
1.建立wxml模板
-
<template name="tabbar">
-
<view class="tabbar_box" style="background-color:{{tabbar.backgroundColor}}; border-top-color:{{tabbar.borderStyle}}; {{tabbar.position == 'top' ? 'top:0' : 'bottom:0'}}">
-
<block wx:for="{{tabbar.list}}" wx:for-item="item" wx:key="index">
-
<navigator class="tabbar_nav" url="{{item.pagePath}}" style="width:{{1/tabbar.list.length*100}}%; color:{{item.selected ? tabbar.selectedColor : tabbar.color}}" open-type="redirect">
-
<image class="tabbar_icon" src="{{item.selected ? item.selectedIconPath : item.iconPath}}"></image>
-
<text>{{item.text}}</text>
-
</navigator>
-
</block>
-
</view>
-
</template>
2.app.wxss裡定義元件樣式
-
.tabbar_box{
-
display: flex;
-
flex-direction: row;
-
justify-content: space-around;
-
position: fixed;
-
bottom: 0;
-
left: 0;
-
z-index: 999;
-
width: 100%;
-
height: 120rpx;
-
border-top: 1rpx solid gray;
-
}
-
.tabbar_nav{
-
display: flex;
-
flex-direction: column;
-
justify-content: center;
-
align-items: center;
-
font-size: 28rpx;
-
height: 100%;
-
}
-
.tabbar_icon{
-
width: 61rpx;
-
height: 61rpx;
-
}
3.app.js定義全域性函式
-
editTabBar: function(){
-
var tabbar = this.globalData.tabbar,
-
currentPages = getCurrentPages(),
-
_this = currentPages[currentPages.length - 1],
-
pagePath = _this.__route__;
-
(pagePath.indexOf('/') != 0) && (pagePath = '/' + pagePath);
-
for(var i in tabbar.list){
-
tabbar.list[i].selected = false;
-
(tabbar.list[i].pagePath == pagePath) && (tabbar.list[i].selected = true);
-
}
-
_this.setData({
-
tabbar: tabbar
-
});
-
},
-
globalData:{
-
userInfo:null,
-
tabbar:{
-
color: "#000000",
-
selectedColor: "#0f87ff",
-
backgroundColor: "#ffffff",
-
borderStyle: "black",
-
list: [
-
{
-
pagePath: "/pages/tabbar/tabbar",
-
text: "專案",
-
iconPath: "/images/item.png",
-
selectedIconPath: "/images/item_HL.png",
-
selected: true
-
},
-
{
-
pagePath: "/pages/address/address",
-
text: "通訊錄",
-
iconPath: "/images/ts.png",
-
selectedIconPath: "/images/ts1.png",
-
selected: false
-
},
-
{
-
pagePath: "/pages/personal/personal",
-
text: "檔案",
-
iconPath: "/images/wjj.png",
-
selectedIconPath: "/images/wjj1.png",
-
selected: false
-
}
-
],
-
position: "bottom"
-
}
-
}
4.在一級頁面引入模板
-
<import src="../tabbar/tabbar.wxml"/>
-
<template is="tabbar" data="{{tabbar}}"/>
5.引入模板的頁面load裡做下處理
getApp().editTabBar();