?我的理解是time是总的时间,分成很多段,rate是每段的时间,每个rate就移动speed的位移,
let animate = setInterval(() => {
if ( this.picBox.style.left == goal || Math.abs(Math.abs(parseFloat(this.picBox.style.left)) - Math.abs(goal)) < Math.abs(speed) ) {
this.picBox.style.left = goal + "px"
clearInterval(animate)
} else {
this.picBox.style.left = parseFloat(this.picBox.style.left) - speed + "px"
}
}, rate)
animate(offset) { // 定义切换时间为1000毫秒 1秒 const time = 1000 //稍微移动为0.1秒 const rate = 100 //计算移动距离 let speed = offset / (time / rate) // 计算目标位置使用parseFloat去掉单位 let goal = parseFloat(this.picBox.style.left) - offset this.animated = true //判断是否到达目标位置 let animate = setInterval(() => { //计算去掉单位的目标绝对值减去目标位置的绝对值小于移动距离的绝对值 if (this.picBox.style.left == goal || Math.abs(Math.abs(parseFloat(this.picBox.style.left)) - Math.abs(goal)) < Math.abs(speed)) { this.picBox.style.left == goal clearInterval(animate) this.animated = false if (parseFloat(this.picBox.style.left) == 0) { this.picBox.style.left = -this.sliders * this.sliderWidth + "px" } else if (parseFloat(this.picBox.style.left) == -(this.sliders + 1) * this.sliderWidth) { this.picBox.style.left = -this.sliderWidth + "px" } } else { //未到达目标位置继续移动 this.picBox.style.left = parseFloat(this.picBox.style.left) - speed + "px" } }, rate) }
我的理解在注释里和你的基本一致