微信小程序swiper(滑塊視圖容器)。其中只可放置swiper-item組件,否則會導致未定義的行為。
wxml:
<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
});
}
})
效果圖如下:
瘋狂滾動
我們看到目前是可用的狀態,但是運行了一段時間之后,它就開始瘋狂滾動。
官方文檔給出的提示
tip: 如果在 bindchange 的事件回調函數中使用 setData 改變 current 值,則有可能導致 setData 被不停地調用,因而通常情況下請在改變 current 值前檢測 source 字段來判斷是否是由於用戶觸摸引起。
所以修改bindTouch
函數加上source
字段判斷
bindTouch: function (e) {
var that = this;
var id = e.detail.current;
if (e.detail.source == 'touch') {
that.setData({
currentTab: id
});
}
}
和scroll-view結合使用
wxml:
<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欄