小程序无限轮播
html
<view class="swiper" bind:touchend="onTouchEnd" bind:touchstart="onTouchStart">
<view class="swiper-wrappe" style="height:200rpx;width:{{(270*arr.length)+(12*arr.length)}}rpx;left:-{{currentIndex*270+(currentIndex*12)}}rpx;transition:{{wrapper_footeract?swiperStyle:''}}">
<view wx:for="{{arr}}" wx:key="index" style="height: 200rpx;margin-right: 12rpx;flex-shrink: 0;flex-grow: 0;width:270rpx" data-item="{{item}}">
{{item.index}}
<image mode="scaleToFill" style="height: 160rpx;width:100%" data-item="{{item}}" src="{{item.url}}" />
</view>
</view>
</view>
js
const app = getApp()
let startX = 0;
let clickMove = true;
Page({
data: {
arr: [{
url: '../../img/img1.png'
},
{
url: '../../img/img2.png'
}, {
url: '../../img/img3.png'
}, {
url: '../../img/img4.png'
}, {
url: '../../img/img5.png'
},
],
wrapper_footeract: true,
swiperStyle: 'left 0.3s',
currentIndex:3
},
onLoad() {
let ArrUn = [];
let movementsLeng = this.data.arr.length;
let {arr} = this.data;
arr.forEach((el, index) => {
el.index = index;
})
// 数组整理,[1,2,3,4,5]=>[3,4,5,1,2,3,4,5,1,2,3]
arr.forEach((el, index) => {
if (index <= 2) {
arr.push(el)
}
if (el.index >= movementsLeng - 3) {
ArrUn.push(el)
}
})
arr = [...ArrUn, ...arr];
this.setData({
arr
})
},
onTouchStart: function (e) {
startX = e.touches[0].clientX
},
onTouchEnd: function (e) {
if (!clickMove) {
return
}
clickMove = false;
setTimeout(() => {
clickMove = true;
}, 300);
let endX = e.changedTouches[0].clientX;
if (endX - startX > 50) {
this.prev()
} else if (startX - endX > 50) {
this.next()
}
},
prev: function () {
let currentIndex = this.data.currentIndex;
console.log(currentIndex, this.data.arr.length)
if (currentIndex > 0) {
this.setData({
currentIndex: currentIndex - 1
})
if (currentIndex == 1) {
setTimeout(() => {
this.setData({
wrapper_footeract: false,
currentIndex: this.data.arr.length - 6,
})
setTimeout(() => {
this.setData({
wrapper_footeract: true,
})
}, 10);
}, 200);
// this.setData({
// currentIndex: this.data.movementArr.length-5
// })
}
}
},
next: function () {
let currentIndex = this.data.currentIndex;
console.log(currentIndex, this.data.arr.length)
if (currentIndex < this.data.arr.length - 3) {
this.setData({
currentIndex: currentIndex + 1
})
if (currentIndex == this.data.arr.length - 4) {
setTimeout(() => {
this.setData({
wrapper_footeract: false,
currentIndex: 3
})
setTimeout(() => {
this.setData({
wrapper_footeract: true,
})
}, 10);
}, 200);
}
}
},
})
css
page{
background: #ededed;
}
.swiper {
height: 200rpx;
display: flex;
flex-direction: row;
overflow-x: hidden;
flex-wrap: nowrap;
position: absolute;
top: 194rpx;
left: 0;
margin: 0 12rpx 0 24rpx;
width: 726rpx;
}
.swiper-wrappe{
display: flex;
width: 100%;
position: absolute;
}