Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
519 views
in Technique[技术] by (71.8m points)

javascript - CSS animation doesn't restart when resetting class

I am using CSS shader + animation. My shader class is defined as follows:

.shader{
-webkit-filter :custom(url(v.vs) mix(url(f.fs) multiply destination-over), 200 200);
-webkit-animation-name: test;
-webkit-animation-duration: 2s;
-webkit-animation-iteration-count: 1
}

I am trying to set/unset the styles(shader+animation) dynamically using jquery through $('#holder').addClass('shader'); and $('#holder').removeClass('shader');

However, the weird thing is when I reset the class (e.g., calling addClass after removeClass), only the shader gets reapplied but the animation doesn't (I have hooked the AnimationStart event to see when my animation starts). Anyone know why this is the case and how I can solve it?

Edit: I added a simplified version of JSfiddle snippet here. Essentially I'm re-applying the animation to a div twice but the actual animation only gets called the first time.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is that, even though you remove and then re-apply the animated class, you do this in the course of a single, blocking function. When your function exits, it appears to the rendering engine that nothing has changed.

One solution (the one that you chose), is to clone the element and destroy the original. This is fine, but if you had any event bindings to the original element (i think) they they will be destroyed too.

Another approach is to remove the animated class from the element, and then wrap the code that re-applies the class inside of a setTimeout() call with a very small delay, e.g.

$('#holder').removeClass('shader');
setTimeout(
    function(){$('#holder').addClass('shader')}
    , 1);

I've tweaked your jsfiddle to use this approach: http://jsfiddle.net/HuFBN/7/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...