如何暂停css动画,然后从暂停点继续运行

How to pause a css animation, and then continue running from the pause point?

本文关键字:暂停 然后 运行 继续 css 何暂停 动画      更新时间:2023-09-26

我正在播放一个具有无限迭代的CSS动画,直到某个点我从java脚本暂停它(使用这里的技术)。

在稍后的时间我恢复动画。问题是动画从开始点重新开始,而不是从暂停前的最后一个点重新开始。

是否有一种方法可以从暂停点继续动画,而不用跳到开始?

编辑:在暂停和恢复之间我还更改了animation duration,参见演示。你应该看到一些"跳跃"。需要解释一下这个奇怪的行为

http://jsfiddle.net/zhang6464/MSqMQ/

根据您提供的文章(http://css-tricks.com/restart-css-animation/

)将animation-play-state css属性切换为paused

我自己刚刚开始深入研究JS,所以肯定有更好的方法来做到这一点,但是如何像这样- Demo(无前缀版本)。

CSS

#box {
    position: relative;
    top: 20px;
    left: 20px;
    width: 100px;
    height: 100px;
    background: #393939;
    animation: move 2s linear infinite;
    animation-play-state: running;
}
@keyframes move {
    100% {
        transform: rotate(360deg);
    }
}

JS:

(function () {
    var box = document.getElementById('box');
    box.onclick = function () {
        if (box.style.animationPlayState === "paused") {
            box.style.animationPlayState = "running";
        } else {
            box.style.animationPlayState = "paused";
        }
    };
})();

基于动画是运行还是暂停,我改变animation-play-state onclick。

编辑:添加css代码。