我编写了一个模拟“实时”元素更新的函数。它随机选择一个元素,然后使用 jQuery UI 库中的 .animate()
和 .effect()
对其进行动画处理。然而,一旦动画结束,元素应该返回到它的原始颜色,但由于某种原因,这并没有发生。在下面找到代码和 JSFiddle .
var decider = Math.round(Math.random() * 6) + 1
var original = $('.tile:nth-child(' + decider + ')').css('background-color');
var a = $('.tile:nth-child(' + decider + ')');
$(a).animate({
backgroundColor: 'green'
}).effect('shake', {
distance: 5,
times: 1
}, 1000).animate({
backgroundColor: original
});
$(a).hover(function () {
$(this).animate({
backgroundColor: original
}).finish();
});
最佳答案
你那里有时间问题。
每次运行 run()
时,它都会根据 DOM 检查 original
颜色。但是,如果 DOM 颜色在检查时仍然是绿色,而不是原始
怎么办?
对于动画结束后发生的事情,使用 animate()
回调函数是一个很好的做法。这样您就知道动画已经完成并处于正确的状态,而不是使用任意时间值。
function run(){
var decider = Math.round(Math.random() * 6) + 1
var original = $('.tile:nth-child(' + decider + ')').css('background-color');
var a = $('.tile:nth-child(' + decider + ')');
$(a).animate({
backgroundColor: 'green'
}).effect('shake', {
distance: 5,
times: 1
}, 1000, function() {
// first animation finish, start second animation
$(this).animate({
backgroundColor: original
}, 1000, function () {
// second animation finish, re-run
run();
});
});
}
关于javascript - .animate() 不会将元素样式改回原始样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33954655/