【问题标题】:Bootstrap animation every 20 seconds每 20 秒启动一次动画
【发布时间】:2026-01-27 10:45:02
【问题描述】:

我在我的应用程序中使用 twitter 引导程序。我要求每 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 秒)。但之后就没有动画了。当我使用断点调试时它可以正常工作。我在这里做错了吗?

【问题讨论】:

  • setInterval有什么问题吗?
  • 我没有使用 setInterval,因为我在我的实际代码中发出了 ajax 请求(在此处将其更改为随机数)。我希望仅在前一个成功时才进行 ajax 调用。 @mu 太短了:我会试着给你做个演示
  • 最好不要在这里使用setInterval,混合setInterval 和AJAX(或任何其他可能需要未知时间或失败的东西)是不愉快的秘诀。
  • @mu 太短:我为你创建了一个 jsfiddle jsfiddle.net/ExsWP。这是我的功能的简单版本,我在这里看到了相同的行为。动画仅在 10 秒后发生。
  • 我仍然看不到动画每 10 秒重复一次。不知道 CoffeeScript。感谢您提供的信息

标签: jquery css animation twitter-bootstrap coffeescript


【解决方案1】:

我想我(终于)看到了问题所在。我们会看看你的小提琴:

$(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-color 在函数的开头将有animate-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/

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

【讨论】:

  • 太棒了。非常感谢。你是个天才:)