我想添加和删除CSS类n时间来显示动画,显示效果n时间,比如设置animation-iteration-count时,不同之处是这里有两个动画,第二个动画带有延迟。
我的想法是使用setTimeout,所以我读了这个堆叠溢出柱,但没有得到预期的结果。
下面是一个带有动画的片段--和一个https://jsfiddle.net/arglab/brhL9h54/ (只显示一次)
$('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>
发布于 2016-03-31 21:51:24
您可以使用setInterval并计算迭代次数。
var n = 3;
var iterationCount = 0;
$('button').click(function(){
clearInterval(animInterval);
var animInterval = setInterval(function(){
$('div').toggleClass('a');
iterationCount++;
if (n == iterationCount)
clearInterval(animInterval);
},4000);
});发布于 2016-03-31 21:51:59
的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/
the js way
如果您坚持按照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()
});发布于 2016-03-31 22:06:21
您可以处理动画结束事件。看看这段代码:
$('div').on('animationend', function (data) {
if (data.originalEvent.animationName === 'b') {
$('div').removeClass('a');
iteration++;
if (iteration < n) {
setTimeout(function () { $('div').addClass('a'); });
} else {
iteration = 0;
$('button').removeAttr('disabled').text('Finished | Again');
}
}
});有参数data.originalEvent.animationName,它指示结束的动画名称。最后一个动画是b,所以您必须删除类并再次添加它。您还必须保留当前的迭代次数和最大迭代次数。在这里查看这个:https://jsfiddle.net/svnwmg3g/
https://stackoverflow.com/questions/36344299
复制相似问题