开发者

add and remove same css class instantly

开发者 https://www.devze.com 2023-01-29 14:02 出处:网络
I have simple html with div and button. Also i have a css class with CSS3 Transition: .animate { -webkit-animation-name: animation;

I have simple html with div and button. Also i have a css class with CSS3 Transition:

.animate
{
    -webkit-animation-name: animation;
    -webkit-animation-duration: 0.3s;
    -webkit-animation-iteration-count: 2;   
}

I want to start animation by clicking a button. So, i wrote a script, which instantly remove and add again .animate class to div, but unfortunately, it doesn't work. Check it out:

("#button").click(function(){ 
    startAnimation(); 
    });

    function startAnimation()
    {
        if ($("#test-div").hasClass('animate')==true)
        {
            $("#test-div").removeClass('animate');  
            startAnimation();
        }
        else
        {
            $("#test-div").addClass('animate'); 
        }   
    }

Why jquery can't remove and instantly add same class? How can i fix that?

And maybe, there is another way to star开发者_开发技巧t css3 transition by clicking any selector?

Thanks.

UPD. I upload script at jsfiddle.net/PfzZN/1/


If the script that makes the change to DOM is in the same thread, for some reason the change will not apply until the thread is finished. So going by your way, the browser will see as if nothing has happened because the 'animate' class is removed and added in the same thread.

As a workaround, will this be good enough?

function startAnimation()
{  
    $("#flash-message").removeClass('animate');  
    setTimeout(function(){
      $("#flash-message").addClass('animate')
    },1);  
}


(My original answer was "deleted" via editing, because it was just plain wrong.)

This seems somewhat like a legitimate bug in Webkit's implementation, or at least something very unexpected. Because if you do a setTimeout, like so:

function startAnimation()
{
    $("#flash-message").toggleClass('animate');    
    if (!$("#flash-message").hasClass('animate'))
    {
        setTimeout(function ()
        {
            $("#flash-message").addClass('animate');    
        }, 1);
    }
}

Then it works. That is, delaying the addition of the class until later seems to make Webkit realize it should re-start the animation.

Not a great solution, but the fact that it was a 1-millisecond setTimeout means at least it's not a timing issue... pretty weird, though.


You can also use JS to listen for animation events. This is tricky, but better than arbitrary timeouts etc that may have no bearing on your animation in the future. Check this out:

http://www.w3.org/TR/css3-animations/#animation-events-

0

精彩评论

暂无评论...
验证码 换一张
取 消