小程序中實現滑塊水平滑動最常用的手段是:通過scroll-view去實現;但是,通過scroll-view實現的滑動可能有時並不是我們想要達到的效果,那麼,還可以通過swiper組件來實現,通過下面可進行同一個功能細節處不同的展示~
一、通過scroll-view實現滑塊滑動
二、通過swiper是實現滑塊滑動
wxml:
<!-- ******************* scroll-view ************************* -->
<view class="descr">用scroll-view組件實現的水平slider(滑塊)</view>
<scroll-view class="scrollView" scroll-x="true">
<block wx:for="{{scrollList}}" wx:key="">
<view class="scrollCont">{{item.scrollCont}}</view>
</block>
</scroll-view>
<!-- ********************* swiper ******************** -->
<view class="descr">用swiper組件實現的水平slider(滑塊)</view>
<!--display-multiple-items同時顯示的滑塊數量 -->
<swiper class="swiperView" display-multiple-items='3'>
<block wx:for="{{swiperList}}" wx:key="">
<swiper-item>
<view class="swiper-imgView">
<image src="{{item.img}}" mode="aspectFill"></image>
<text class="swiper-text">{{item.descr}}</text>
</view>
</swiper-item>
</block>
</swiper>
wxss:
.swiperView,.scrollView{
width:720rpx;
margin: 0 auto;
}
.descr{
height:80rpx;
line-height: 80rpx;
font-size: 36rpx;
text-align: center;
font-weight: bold;
background-color: cornflowerblue;
margin:20rpx 0;
margin-top:100rpx;
}
/* 滑塊 */
.scrollView{
white-space: nowrap;
}
.scrollCont{
height:200rpx;
width: 200rpx;
display: inline-block;
text-align: center;
margin-right:15rpx;
background-color: cyan;
border:1rpx solid gainsboro;
}
/* 輪播 */
.swiperView{
height:200rpx;
}
.swiper-imgView{
height: 100%;
border:3rpx solid #fff;
padding:0 1.5rpx;
}
.swiper-imgView>image{
width:100%;
height:100%;
}
js:
Page({
data: {
scrollList: [
{ "scrollCont": "滑塊1" },
{ "scrollCont": "滑塊2" },
{ "scrollCont": "滑塊3" },
{ "scrollCont": "滑塊4" },
{ "scrollCont": "滑塊5" },
{ "scrollCont": "滑塊6" },
{ "scrollCont": "滑塊7" },
{ "scrollCont": "滑塊8" },
],
swiperList: [
{ "img": "https://images.unsplash.com/photo-1551334787-21e6bd3ab135?w=640" },
{ "img": "https://images.unsplash.com/photo-1551334787-21e6bd3ab135?w=640" },
{ "img": "https://images.unsplash.com/photo-1551334787-21e6bd3ab135?w=640" },
{ "img": "https://images.unsplash.com/photo-1551334787-21e6bd3ab135?w=640" },
{ "img": "https://images.unsplash.com/photo-1551334787-21e6bd3ab135?w=640" },
{ "img": "https://images.unsplash.com/photo-1551334787-21e6bd3ab135?w=640" }
]
},
onLoad: function () {
}
})
效果:
可以從中看出,用scroll-view實現的滑塊不能夠向滑動的方向對齊,而swiper是可以的。下面以圖說明可能更直觀!
我向左滑動爲例,上面圖片中有兩個豎直的紅線,上面的沒有停留在滑塊的左邊線上,下面的一條停留在了滑塊的左邊線上。即swiper是以塊爲單位滑動的,scroll-view則不是,有時會停留在某一個塊上,這樣顯得不是太友好~