当然,使用
window.setInterval() 也可以实现这个效果,而且会稍微好理解一点,因为没有用到递归:
methods:{
move(offset, direction) {
direction === -1 ? this.currentIndex++ : this.currentIndex--
if (this.currentIndex > 5) this.currentIndex = 1
if (this.currentIndex < 1) this.currentIndex = 5 const destination = this.distance + offset * direction
this.animate(destination, direction)
},
animate(des, direc) {
const temp = window.setInterval(() => {
if ((direc === -1 && des < this.distance) || (direc === 1 && des > this.distance)) {
this.distance += 30 * direc
} else {
window.clearInterval(temp)
this.distance = des
if (des < -3000) this.distance = -600
if (des > -600) this.distance = -3000
}
}, 20)
}
}
实现出来的效果如下:
四、简单节流一下
写到这里,效果是出来了,但是会有一点问题,如果多次快速点击,就会有可能出现下面这种情况:
出现这种情况的原因很简单,因为是使用定时器过渡,所以连续快速点击就会出现错乱,简单节流一下就好了: 在过渡完成之前点击箭头无效,其实就是设了一个闸,第一次点击把闸打开,在闸再次打开之前,让一部分代码无法执行,然后再在恰当的时机把闸打开。
我们把这个闸设在move函数里:
move(offset, direction) {
if (!this.transitionEnd) return //这里是闸
this.transitionEnd = false //开闸以后再把闸关上
direction === -1 ? this.currentIndex++ : this.currentIndex--
if (this.currentIndex > 5) this.currentIndex = 1
if (this.currentIndex < 1) this.currentIndex = 5 const destination = this.distance + offset * direction
this.animate(destination, direction)
}
this.transitionEnd 是这个闸的钥匙,我们把它放到data里:
this.transitionEnd: true
这个闸一开始默认的状态是开着的,第一次点击以后,这个闸就关上了, this.tranisitonEnd = false ,在再次打开之前,后面的代码都执行不了。接下来就是在恰当的时机把这个闸打开,而这个恰当的时机就是过渡完成时,也就是在 animate函数 里:
animate(des, direc) {
if (this.temp) {
window.clearInterval(this.temp)










