我想添加和删除 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()
});
关于javascript - 如何使用 setTimeout 添加和删除 CSS 类 n 次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36344299/