所以我有一个类,其中包含一些使轮播工作的功能。但是按下下一个按钮会快速删除上一个动画,然后开始下一个动画,因此我想让该按钮等待动画结束。 CSS内的动画是0.6秒,但是当我快速单击按钮时,我在goNext函数内设置的时间太长了。我在这里做错了什么? index.js
let carousel = document.getElementById("carousel");
let seats = document.querySelectorAll("ul > li");
if (seats.length === 1)
carousel.style.left = 0;
class SLID {
constructor() {
this.nextDisable = true;
this.changeNextDisable = this.changeNextDisable.bind(this);
}
changeNextDisable() {
this.nextDisable = false;
}
goToNext() {
if(this.nextDisable===false){
this.nextDisable = true;
var el, i, j, new_seat, ref;
el = document.querySelector("ul > li.is-ref");
el.classList.remove('is-ref');
new_seat = el.nextElementSibling || seats[0];
new_seat.classList.add('is-ref');
new_seat.style.order = 1;
for (i = j = 2, ref = seats.length; (2 <= ref ? j <= ref : j >= ref); i = 2 <= ref ? ++j : --j) {
new_seat = new_seat.nextElementSibling || seats[0];
new_seat.style.order = i;
}
carousel.classList.remove('toPrev');
carousel.classList.add('toNext');
carousel.classList.remove('is-set');
return setTimeout(()=> {
this.changeNextDisable();
carousel.classList.add('is-set');
}, 60);
}
goToPrev() {
var el, i, j, new_seat, ref;
el = document.querySelector("ul > li.is-ref");
el.classList.remove('is-ref');
new_seat = el.previousElementSibling || seats[seats.length - 1];
new_seat.classList.add('is-ref');
new_seat.style.order = 1;
for (i = j = 2, ref = seats.length; (2 <= ref ? j <= ref : j >= ref); i = 2 <= ref ? ++j : --j) {
new_seat = new_seat.nextElementSibling || seats[0];
new_seat.style.order = i;
}
carousel.classList.remove('toNext');
carousel.classList.add('toPrev');
carousel.classList.remove('is-set');
return setTimeout((function () {
return carousel.classList.add('is-set');
}), 50);
}
}
}
let s = new SLID();
document.getElementById("nextButton").addEventListener("click", () => {
s.goToNext();
});
document.getElementById("prevButton").addEventListener("click", () => {
s.goToPrev();
});
答案 0 :(得分:0)
根据您的动画类型(transition
或animation
),您可以替换
return setTimeout(()=> {
this.changeNextDisable();
carousel.classList.add('is-set');
}, 60);
(并尝试避免这种情况):
carousel.addEventListener("animationend", () => {
this.changeNextDisable();
carousel.classList.add('is-set');
}, {
once: true,
});
或
carousel.addEventListener("transitionend", () => {
this.changeNextDisable();
carousel.classList.add('is-set');
}, {
once: true,
});
与goToPrev
方法相同。
答案 1 :(得分:0)
您告诉我们CSS动画的持续时间为0.6秒,即600毫秒,而不是60或50毫秒,这是您将setTimeout
延迟设置为的时间。
所以:
return setTimeout(()=> {
this.changeNextDisable();
carousel.classList.add('is-set');
}, 600);
// ^^^^
话虽如此,您应该调查一下transactionend
事件,因为那样您就不必知道CSS转换需要多长时间。
它看起来像这样:
const done = () => {
carousel.removeEventListener("transactionend", done);
this.changeNextDisable();
carousel.classList.add('is-set');
}
return carousel.addEventListener("transactionend", done);