在微信小程序開發文檔中提供了在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 }); }, })
效果圖:

list.gif
作者:IT小白_
鏈接:https://www.jianshu.com/p/1a3405f77654
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。