微信小程序swiper(滑塊視圖容器)。其中只可放置swiper-item組件,不然會致使未定義的行爲。css
wxml:html
<view class="swiper-tab"> <view class="swiper-tab-item {{currentTab==0 ? 'on' : ''}}" data-current="0" bindtap="swichTab">tab1</view> <view class="swiper-tab-item {{currentTab==1 ? 'on' : ''}}" data-current="1" bindtap="swichTab">tab2</view> </view> <!-- 這裏根據設備屏幕的高度動態設置組件的高度 --> <swiper current="{{currentTab}}" duration="300" style="height:{{clientHeight?clientHeight+'px':'auto'}}" bindchange="bindTouch"> <swiper-item> <view style="text-align: center;">view1</view> </swiper-item> <swiper-item> <view style="text-align: center;">view2</view> </swiper-item> </swiper>
wxss:小程序
.swiper-tab { width: 100%; text-align: center; border-bottom: 1px solid #b2b2b2; } .swiper-tab-item { width: 50%; display: inline-block; font-size: 12pt; color: #666; } .on { color: #09bb07; border-bottom: 5rpx solid #09bb07; }
js:微信小程序
Page({ data: { clientHeight: 0, currentTab: 0 }, onLoad: function (options) { var that = this; // 動態獲取設備屏幕高度 wx.getSystemInfo({ success: function (res) { that.setData({ clientHeight: res.windowHeight }); } }); }, swichTab: function (e) { var that = this; if (this.data.currentTab === e.target.dataset.current) { return false; } else { var id = e.target.dataset.current; that.setData({ currentTab: id }) } }, bindTouch: function (e) { var that = this; var id = e.detail.current; that.setData({ currentTab: id }); } })
效果圖以下:微信
咱們看到目前是可用的狀態,可是運行了一段時間以後,它就開始瘋狂滾動。xss
官方文檔給出的提示函數
tip: 若是在 bindchange 的事件回調函數中使用 setData 改變 current 值,則有可能致使 setData 被不停地調用,於是一般狀況下請在改變 current 值前檢測 source 字段來判斷是不是因爲用戶觸摸引發。this
因此修改bindTouch
函數加上source
字段判斷code
bindTouch: function (e) { var that = this; var id = e.detail.current; if (e.detail.source == 'touch') { that.setData({ currentTab: id }); } }
wxml:xml
<view> <view class="swiper-tab"> <view class="swiper-tab-item {{currentTab==0 ? 'on' : ''}}" data-current="0" bindtap="swichTab">tab1</view> <view class="swiper-tab-item {{currentTab==1 ? 'on' : ''}}" data-current="1" bindtap="swichTab">tab2</view> </view> <swiper current="{{currentTab}}" duration="300" style="height:{{clientHeight?clientHeight+'px':'auto'}}" bindchange="bindTouch"> <swiper-item> <scroll-view scroll-y style="height:100%"> <view>view</view> ... </scroll-view> </swiper-item> <swiper-item> <view style="text-align: center;">view2</view> </swiper-item> </swiper> </view>
可是會發現它的樣式有問題
滾動條已經拖到底了可是仍是現實不全。由於設置的高度多了一個頭部tab欄的高度,因此這裏不能設爲100%
,也須要動態設置。
<scroll-view scroll-y style="height:100%" style="height: {{clientHeight?(clientHeight-24) +'px':'auto'}}">
page overflow:hidden
能夠固定頭部tab欄