2 回答

TA貢獻1824條經驗 獲得超5個贊
試試這個:
function flash(index, delay){
setTimeout( function() {
flashingSquare = document.getElementById(index);
flashingSquare.classList.add('flashing');
flashingSquare.addEventListener('animationend', function() {
flashingSquare.classList.remove('flashing');
}, delay);
});
}
不要刪除動畫,刪除 class。
動畫完成后直接刪除類。所以瀏覽器有時間處理所有事情。當您在需要動畫之前直接添加類時,瀏覽器可以觸發所有需要的步驟來執行此操作。
您刪除和添加課程的嘗試很好,但速度很快。我認為瀏覽器和 DOM 優化了你的步驟并且什么都不做。

TA貢獻1752條經驗 獲得超4個贊
經過一番研究,我想出了一個解決方法。我重寫了函數,以便 setTimeout 嵌套在 for 循環中,setTimeout 嵌套在立即調用的函數表達式中(我仍然不完全理解,但是嘿,如果它有效)。新函數如下所示:
/*
function to display game sequence
length can be any integer greater than 1
speed is time between flashes in ms and can presently be set to 1000, 750, 500 and 250.
animation length for each speed is set by a corresponding speed class
in CSS main - .flashing1000 .flashing750 .flashing500 and .flashing250
*/
function displaySequence(length, speed) {
var sequence = generateSequence(length);
console.log(sequence);
for (i = 0; i < sequence.length; i++) {
console.log(sequence[i]);
// immediately invoked function expression
(function(i) {
setTimeout( function () {
var sq = document.getElementById(sequence[i]);
sq.classList.add('flashing' + speed.toString());
sq.addEventListener('animationend', function() {
sq.classList.remove('flashing' + speed.toString());
})
}, (speed * i))
})(i);
}
}
每個類的 CSS:
@keyframes flash {
0% {
background: #333;
}
50% {
background: orange
}
100% {
background: #333;
}
}
.flashing1000 {
animation: flash 975ms;
}
.flashing750 {
animation: flash 725ms;
}
.flashing500 {
animation: flash 475ms;
}
.flashing250 {
animation: flash 225ms;
}
我知道有一些懶惰的解決方法,但效果很好。
添加回答
舉報