停止CSS动画,但让它的当前迭代完成 [英] Stopping a CSS animation but letting its current iteration finish

查看:130
本文介绍了停止CSS动画,但让它的当前迭代完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下HTML:

<div class="rotate"></div>​

和以下CSS:

@-webkit-keyframes rotate {
  to { 
    -webkit-transform: rotate(360deg);
  }
}
.rotate {
    width: 100px;
    height: 100px;
    background: red;
    -webkit-animation-name:             rotate;
    -webkit-animation-duration:         5s;
    -webkit-animation-iteration-count:  infinite;
    -webkit-animation-timing-function:  linear;
}​



我想知道是否有一种方法动画,但让它完成它的当前迭代(最好通过改变一个或几个CSS属性)。我已经尝试将 -webkit-animation-name 设置为空值,但是会导致元素以刺耳的方式跳回到其原始位置。我也尝试将 -webkit-animation-iteration-count 设置为 1 ,但是做同样的事情。 p>

I want to know if there is a way (using JavaScript) to stop the animation but let it finish its current iteration (preferably by changing one or a few CSS properties). I have tried setting -webkit-animation-name to have a blank value but that causes the element to jump back to its original position in a jarring fashion. I have also tried setting -webkit-animation-iteration-count to 1 but that does the same thing.

推荐答案

在接收到 animationiteration 事件时停止动画。类似这样的东西(使用jQuery):

Stop the animation upon receiving an animationiteration event. Something like this (using jQuery):

CSS

@-webkit-keyframes rotate {
  to {
    -webkit-transform: rotate(360deg);
  }
}
.rotate {
    width: 100px;
    height: 100px;
    background: red;
}
.rotate.anim {
    -webkit-animation-name:             rotate;
    -webkit-animation-duration:         5s;
    -webkit-animation-iteration-count:  infinite;
    -webkit-animation-timing-function:  linear;
}

HTML

<div class="rotate anim">TEST</div>
<input id="stop" type="submit" value="stop it" />

JS

$("#stop").click(function() {
    $(".rotate").one('animationiteration webkitAnimationIteration', function() {
        $(this).removeClass("anim");
    });
});

小提琴: http://jsfiddle.net/sSYYE/1/

请注意,我使用 .one 这里(不是 .on ),这样处理程序只运行一次。这样,动画可以稍后重新启动。

Note that I'm using .one here (not .on) so that the handler only runs once. That way, the animation can later be restarted.

这篇关于停止CSS动画,但让它的当前迭代完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆