我有以下循环,应该为 formInputs
中的每个元素添加一个类,等待 300 毫秒,然后根据 flashCount
中定义的次数再次删除它。所以在本例中是 2 次。
但由于某种原因,delay(300)
不起作用,而且我的循环速度非常快,我什至看不到它的视觉效果。
我该如何解决这个问题?
for (var key in formInputs) {
if (formInputs.hasOwnProperty(key) && !formInputs[key]["input"].val()) {
var flashCount = 2;
for (var i = 0; i < flashCount; i++) {
formInputs[key]["input"].addClass("hovered").delay(300).removeClass("hovered");
}
}
}
最佳答案
问题是 jQuery 仅在其内部动画队列中使用delay
。由于 addClass
和 removeClass
不是动画,因此您必须自己将它们添加到队列中。就像这样:
for (var key in formInputs) {
if (formInputs.hasOwnProperty(key) && !formInputs[key]["input"].val()) {
var flashCount = 2;
for (var i = 0; i < flashCount; i++) {
// Add the function to jQuery's animation queue instead of removing the class straight away
formInputs[key]["input"].addClass("hovered").delay(300).queue(function(next){
// Remove the `hovered` class when the queue gets to this
$(this).removeClass("hovered");
// Call the next item in the queue
next();
});
}
}
}
显然我无法测试这个,但应该可以。
关于javascript - For循环忽略延迟(300),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25612619/