每20秒进行一次引导动画

乌萨

我在我的应用程序中使用了twitter bootstrap。我需要每20秒对图标进行动画处理。

这是我的代码。它在咖啡脚本中。但是它非常基础,可以很容易地与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秒)。但此后不进行动画处理。当我使用断点调试时,它可以正常工作。我在这里做错什么了吗?

亩太短

我想我(终于)看到了问题。我们将看您的小提琴:

$(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一次动画。那将导致我们尝试以下CoffeeScript版本:

animateIcon = ->
    $('#change-color').removeClass('animate-color')
    $('#change-color').addClass('animate-color')
    setTimeout(animateIcon, 20000)
$(animateIcon)

看起来它应该重新添加animate-color该类并重新触发CSS动画,但事实并非如此。为什么不?好吧,第二次animateIcon运行#change-coloranimate-color在函数的开头,并且animate-color在浏览器再次获得控制权时在结尾;由于#change-color的类没有更改(即,之前和之后的类相同),因此什么也不会发生。

要解决该问题,您需要使浏览器以某种方式欺骗类,使他们认为类实际上已更改。实现这一目标的一种方法是这样的:

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

那么,我们如何将控制权交还给浏览器?一个setTimeout(..., 0)电话是一个常见的伎俩。将以上内容转换为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/

抱歉耽搁了,我忘记了这个问题。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章