我在我的应用程序中使用 twitter bootstrap。我需要每 20 秒为一个图标设置动画。
这是我的代码。它是 CoffeeScript 。但它非常基础,很容易与 JavaScript 相关。
@updateCountIndicator = () ->
data = Math.floor (Math.random() * 10) + 1
countIndicator = $("#count-indicator")
countIcon = $("#count-icon")
countIcon.removeClass("icon-animated-vertical")
countIndicator.html data
countIcon.toggleClass "icon-animated-vertical"
timedCountUpdate()
@timedCountUpdate = () ->
setTimeout(updateCountIndicator, 20000)
问题是,图标第一次动画(页面刷新后 20 秒)。但之后就不再动画了。当我使用断点调试时它工作正常。我在这里做错了什么吗?
最佳答案
我想我(终于)看到了问题所在。我们会看看你的 fiddle :
$(document).ready(function(){
setTimeout(animateIcon, 20000);
});
function animateIcon() {
$("#change-color").addClass("animate-color");
setTimeout(animateIcon, 20000);
}
然后从那里开始。每次animateIcon
被调用时,它将:
$("#change-color").addClass("animate-color");
但是如果 #change-color
则没有任何作用已经有animate-color
类,因此您只能看到 animate-color
动画一次。这将 Bootstrap 我们尝试这个 CoffeeScript 版本:
animateIcon = ->
$('#change-color').removeClass('animate-color')
$('#change-color').addClass('animate-color')
setTimeout(animateIcon, 20000)
$(animateIcon)
看起来应该重新添加 animate-color
class 并重新触发 CSS 动画,但它不会。为什么不?嗯,第二次了animateIcon
运行,#change-color
将有animate-color
在函数的开头,它将有 animate-color
最后当浏览器再次获得控制权时;自 #change-color
的类没有改变(即之前和之后具有相同的类),什么也不会发生。
为了解决这个问题,您需要欺骗浏览器,让其认为类实际上已更改。实现这一目标的一种方法如下:
- 重置
#change-color
上的类别和颜色. - 将控制权交还给浏览器。
- 添加
animate-color
. - 重新启动计时器。
- 将控制权交还给浏览器。
那么我们如何将控制权交还给浏览器呢?一个setTimeout(..., 0)
call 是一个常见的技巧。将上面的内容转换为 CoffeeScript 可以得到:
addClassAndRestart = ->
$('#change-color').addClass('animate-color')
setTimeout(animateIcon, 20000)
animateIcon = ->
$('#change-color').removeClass('animate-color').css('background', 'transparent')
setTimeout(addClassAndRestart, 0)
$(animateIcon)
.css('background', 'transparent')
可能需要也可能不需要,但这就是#change-color
以开头,所以我添加了它。
演示:http://jsfiddle.net/ambiguous/BByJD/
很抱歉耽搁了时间,我忘记了这个问题。
关于jquery - 每 20 秒启动一次动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18339382/