【问题标题】:Stopping a CSS animation but letting its current iteration finish停止 CSS 动画,但让其当前迭代完成
【发布时间】:2012-10-15 04:49:34
【问题描述】:

我有以下 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;
}​

我想知道是否有办法(使用 JavaScript)来停止动画,但让它完成当前的迭代(最好通过更改一个或几个 CSS 属性)。我尝试将-webkit-animation-name 设置为空白值,但这会导致元素以不和谐的方式跳回其原始位置。我也尝试将-webkit-animation-iteration-count 设置为1,但效果相同。

【问题讨论】:

  • 作为替代方案,我建议使用 javascript 动画。
  • 计算当前迭代并将迭代计数设置为该值,是否可能/可跟踪?
  • 尝试为 div 创建另一个类,使其样式位于您希望它完成的位置,然后使用 javascript,在动画到达您想要的点时将该类应用于 div它停止。

标签: css animation


【解决方案1】:

收到animationiteration 事件后停止动画。像这样的东西(使用 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 (JQuery)

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

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

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

【讨论】:

  • 我做了一个版本,它也可以根据要求重新启动动画。 animationiteration webkitAnimationIteration 事件的事件处理程序必须在触发后禁用。 jsfiddle.net/MNQcN/1
  • 实际上,这就是我在原始代码中使用.one() 的原因(您已更改)。 .one() 绑定一次性事件处理程序。使用onejsfiddle.net/MNQcN/3
  • 哦,出于某种原因,我认为这是一个错误。对此感到抱歉。
【解决方案2】:

您的意思是您希望动画在结束时停在原处而不跳回其原始位置?

那么你想要:

动画从一个地方移动到另一个地方并让它停留在那里: 动画填充模式:转发;

查看此链接:

http://www.w3schools.com/cssref/css3_pr_animation-fill-mode.asp

【讨论】:

    猜你喜欢
    • 2017-01-02
    • 1970-01-01
    • 1970-01-01
    • 2012-04-29
    • 2012-04-19
    • 2016-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多