javascript - 如何使用 setTimeout 添加和删除 CSS 类 n 次?

标签 javascript jquery css

我想添加和删除 CSS 类 n 次以显示动画,显示效果 n 次,就像您设置 animation-iteration -count,区别在于这里我有两个动画,第二个有延迟。

我的想法是使用setTimeout,所以我读了this Stack Overflow post但我没有得到预期的结果。

这是一个片段 - 和一个 JSfiddle - 带有动画(显示一次)

$('button').click(function(){
  $('div').addClass('a');
  
  $(this).attr('disabled','true').text('Started');
  
  setTimeout(function(){
    $('div').removeClass('a');
    
    $('button').removeAttr('disabled').text('Finished | Again');
  },6000);
});
div {
  width: 100px; height: 100px; background: red;
}

.a {
  animation: a 2s linear, b 2s 2s linear;
}

@keyframes a {
  from { background: red; }
  to { background: blue; }
}

@keyframes b {
  from { background: blue; }
  to { background: black; }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div></div>
<button>Start</button>

最佳答案

css 方式

用 js 重复动画对我来说似乎是错误的。有 animation-iteration-count 属性,并且可以关闭添加多个 @keyframes 你应该能够实现你所追求的。对于您的示例代码,它甚至非常简单(尽管我怀疑您的真实动画可能有点不同:

.a {
  animation: a 2s linear 5 alternate;
}

@keyframes a {
  0% { background: red; }
  50% { background: blue; }
  100% { background: black; }
}

如果您找不到仅使用 css 实现动画的方法,请随时发布您的实际动画。 https://jsfiddle.net/brhL9h54/4/

js方式

如果您坚持采用 js 方式,则需要确保在每个循环后重置超时。这可以通过使用递归调用函数来完成。在计数器的帮助下,您可以轻松控制要运行的次数。顺序如下:

$('button').click(function(){
  $('div').addClass('a');

  $(this).attr('disabled','true').text('Started');

  var counter = 5;

  function repeater() {
    if (counter >= 0) {
       $('div').toggleClass('a');
       counter--;
       // start new cycle
       setTimeout(repeater, 3000);
    } else {
       // cleanup
       $('button').removeAttr('disabled').text('Finished | Again');
    }
  }

  // boot the repeater
  repeater()
});

https://jsfiddle.net/brhL9h54/7/

关于javascript - 如何使用 setTimeout 添加和删除 CSS 类 n 次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36344299/

相关文章:

javascript - 如何正确使用 if/else 结构从右侧动画新内容并通过向左滑动摆脱旧内容?

javascript - 如何在 HTML 视频源中调用 javascript 变量

javascript添加两个文本框值并在asp.net中显示在第三个

javascript - 更改跨度文本非常慢

css - 如果超过 6 个字母,则 div Angular (45deg) 中的旋转文本会中断。如何永远居中?

javascript - 未捕获的类型错误 : Cannot read property 'nodeName' of null

jquery - knockout : filling array property in model with jQuery on document ready

jquery - 如何使用 JQuery 删除具有特定单词 id 或类的 div 并保留内部内容

javascript - 根据选定的 radio 输入显示和隐藏 div

asp.net - 确认 javascript 和 ASP.net 中的警告框,如 Hotmail