在微信小程序开发文档中提供了在json文件中配置tab切换的方法,那便是tabBar,其底层原理就是三个页面的来回切换,而且此tab只能放在网页底部或者头部,局限性非常大。那么当我们有一个需求是实现一个页面下tab切换功能而并非多个页面,在微信小程序中又该怎么做呢?
话不多说,上源码:
WXML:
<view class="swiper-tab">
<view class="swiper-tab-list {{currentTab==0 ? \'on\' : \'\'}}" data-current="0" bindtap="swichNav">产品</view>
<view class="swiper-tab-list {{currentTab==1 ? \'on\' : \'\'}}" data-current="1" bindtap="swichNav">金融</view>
<view class="swiper-tab-list {{currentTab==2 ? \'on\' : \'\'}}" data-current="2" bindtap="swichNav">理财</view>
</view>
<swiper current="{{currentTab}}" class="swiper-box" duration="300" style="height:{{winHeight - 31}}px" bindchange="bindChange">
<swiper-item>
<view>产品</view>
</swiper-item>
<swiper-item>
<view>金融</view>
</swiper-item>
<swiper-item>
<view>理财</view>
</swiper-item>
</swiper>
用三元表达式判断currentTab==Num是否为真,如果为真,动态添加on类名,执行标记样式,这样就实现了上面list列表的切换,至于内容重定义了data下的currentTab,让其与之对应显示,这样一个简单的tab切换功能就实现了,而且不受位置的限制,更改css样式可随意布局
=================
WXSS:
.swiper-tab{
width: 100%;
text-align: center;
line-height: 80rpx;}
.swiper-tab-list{ font-size: 30rpx;
display: inline-block;
width: 33.33%;
color: #777777;
}
.on{ color: blue;
border-bottom: 3rpx solid blue;}
.swiper-box{ display: block; height: 100%; width: 100%; overflow: hidden; }
.swiper-box view{
text-align: center;
}
JS:
Page({
data: {
winWidth: 0,
winHeight: 0,
currentTab: 0,
},
onLoad: function() {
var that = this;
/**
* 获取当前设备的宽高
*/
wx.getSystemInfo( {
success: function( res ) {
that.setData( {
winWidth: res.windowWidth,
winHeight: res.windowHeight
});
}
});
},
// tab切换逻辑
swichNav: function( e ) {
var that = this;
if( this.data.currentTab === e.target.dataset.current ) {
return false;
} else {
that.setData( {
currentTab: e.target.dataset.current
})
}
},
bindChange: function( e ) {
var that = this;
that.setData( { currentTab: e.detail.current });
},
})
效果图:
作者:IT小白_
链接:https://www.jianshu.com/p/1a3405f77654
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
请发表评论