前言:小程序官方swiper组件并未提供带左右箭头功能,但有些时候还是想把左右箭头添加上,今天连胜老师就给大家分享一下自己的实现方式。
思路很简单:在swiper组件内部添加两个image组件,绑定点击事件,动态改变swiper中的current值。不废话,主要看代码:
WXML:
代码语言:javascript复制<swiper indicator-dots="{{swiper.indicatorDots}}"
autoplay="{{swiper.autoplay}}" interval="{{swiper.interval}}" duration="{{swiper.duration}}" current='{{swiper.current}}' circular="true">
<block wx:for="{{swiper.imgUrls}}">
<swiper-item>
<image src="{{item}}" class="slide-image" width="355" height="150"/>
</swiper-item>
</block>
<image class='prev arrow' bindtap='prevImg' src='/images/prev.jpg' />
<image class='next arrow' bindtap='nextImg' src='/images/next.jpg' />
</swiper>
WXSS:
代码语言:javascript复制swiper{
position: relative;
height: 300rpx;
}
swiper image{
display: block;
width: 100%;
height: 300rpx;
cursor: pointer;
}
swiper .arrow{
width: 30rpx;
height: 46rpx;
}
swiper .prev{
position: absolute;
left: 0;
top: 50%;
transform: translate(0, -50%);
cursor: pointer;
}
swiper .next{
position: absolute;
right: 0;
top: 50%;
transform: translate(0, -50%);
}
JS:
代码语言:javascript复制//index.js
Page({
data: {
swiper: {
imgUrls: [
'/images/swiper01.jpg',
'/images/swiper02.jpg',
'/images/swiper03.jpg'
],
indicatorDots: true,
autoplay: false,
interval: 5000,
duration: 1000,
current: 0,
}
},
prevImg: function(){
var swiper = this.data.swiper;
var current = swiper.current;
swiper.current = current>0 ? current-1 : swiper.imgUrls.length-1;
this.setData({
swiper: swiper,
})
},
nextImg: function () {
var swiper = this.data.swiper;
var current = swiper.current;
swiper.current = current < (swiper.imgUrls.length - 1) ? current 1 : 0;
this.setData({
swiper: swiper,
})
}
})
看一下完成之后的效果:
貌似还不错,有用到这功能的同学,直接copy代码运行即可~