jquery - 每 20 秒启动一次动画

标签 jquery css animation twitter-bootstrap coffeescript

我在我的应用程序中使用 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的类没有改变(即之前和之后具有相同的类),什么也不会发生。

为了解决这个问题,您需要欺骗浏览器,让其认为类实际上已更改。实现这一目标的一种方法如下:

  1. 重置 #change-color 上的类别和颜色.
  2. 将控制权交还给浏览器。
  3. 添加animate-color .
  4. 重新启动计时器。
  5. 将控制权交还给浏览器。

那么我们如何将控制权交还给浏览器呢?一个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/

相关文章:

html - 最小高度和最小宽度应始终相等

javascript - 可以使用网络 worker 来使计时更加准确吗

ios - 我们如何在 3D 空间中同时旋转 2 个 UIView 平面

javascript - 更新服务中的新值

jquery自动完成取消焦点事件

java - 如何使用 Struts2 jQuery 从 external.js 获取 session 值

javascript - JavaScript 闭包错误

css - * :before, *的目的:在没有内容属性的规则之后

html - 保持位置固定 div 高于其他位置相对 div

android - viewflipper仅下一个动画