小程序中实现滑块水平滑动最常用的手段是:通过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则不是,有时会停留在某一个块上,这样显得不是太友好~