Turn Off CSS3 Animation With jQuery?

2019-02-16 08:56发布

I have an object that has an animation when the page is loaded:

.logo-mark {
        -webkit-animation: spin 2s 1 cubic-bezier(0.000, 0.000, 0.230, 1.000);
            -moz-animation: spin 2s 1 cubic-bezier(0.000, 0.000, 0.230, 1.000);
            -ms-animation: spin 2s 1 cubic-bezier(0.000, 0.000, 0.230, 1.000);
            animation: spin 2s 1 cubic-bezier(0.000, 0.000, 0.230, 1.000);
    }

At a certain time, I want JavaScript to turn on a specific animation that occurs endlessly, until JavaScript stops said animation. So I simply made another class named .logo-loading, and at certain times, jQuery does an addClass and a removeClass.

.logo-loading {
            -webkit-animation: spin 4s infinite linear;
                -moz-animation: spin 4s infinite linear;
                -ms-animation: spin 4s infinite linear;
                animation: spin 4s infinite linear;
        }

However, when JavaScript removes the class, the object just keeps rotating no matter what. Is there anything I can do here?

3条回答
我想做一个坏孩纸
2楼-- · 2019-02-16 09:33

If you want to pause an animation (and then resume from the point that it was paused) you could toggle it's play state with this CSS property:

.paused {
   -ms-animation-play-state:paused;
   -o-animation-play-state:paused;
   -moz-animation-play-state:paused;
   -webkit-animation-play-state:paused;
  animation-play-state: paused;
}

You could then use jquery to toggle the paused class:

$("#animatedElement").click(function(e){ 
  $(e.currentTarget).toggleClass("paused"); 
});

See this example that actually pauses without javascript: http://jsfiddle.net/fRzwS/

And this post on forrst from the fiddle's author: http://forrst.com/posts/How_To_Pause_CSS_Animations-0p7

查看更多
Deceive 欺骗
3楼-- · 2019-02-16 09:37

This works as you'd expect in Firefox, see this jsFiddle:

So I modified your example (only retained -moz- ones as it's Firefox) to 1s cycles, I start the spinning and then end it after 3.6s. It all works fine, Firefox 11.0 on Xubuntu 11.10.

If you are not using Firefox, can you try in Firefox to confirm they (both your and my examples) work there on your machine? It might be a browser-specific "feature".

查看更多
Lonely孤独者°
4楼-- · 2019-02-16 09:44

You can just override that CSS properties with "none" to every animation

function stopAnimation(element)
{
    $(element).css("-webkit-animation", "none");
    $(element).css("-moz-animation", "none");
    $(element).css("-ms-animation", "none");
    $(element).css("animation", "none");
}

so you can stop animation simply calling this function...

查看更多
登录 后发表回答