2015-10-19 57 views
3

當我使用:jquery:addClass,removeClass:動畫只有一次:爲什麼?

$("#passwordConfig").removeClass('shake animated').addClass('shake animate'); 

這隻有一次。

我需要添加一些timeOut使其運行儘可能多的次數,我想!

$("#passwordConfig").removeClass('shake animated'); 
        setTimeout(function() { 
         $("#passwordConfig").addClass('shake animated'); 
        }, 50); 

任何想法爲什麼?

CSS:

.animated { 
    -webkit-animation-duration: 1s; 
    animation-duration: 1s; 
    -webkit-animation-fill-mode: both; 
    animation-fill-mode: both; 
} 

@-webkit-keyframes shake { 
    0%, 100% { 
    -webkit-transform: translate3d(0, 0, 0); 
    transform: translate3d(0, 0, 0); 
    } 

    10%, 30%, 50%, 70%, 90% { 
    -webkit-transform: translate3d(-10px, 0, 0); 
    transform: translate3d(-10px, 0, 0); 
    } 

    20%, 40%, 60%, 80% { 
    -webkit-transform: translate3d(10px, 0, 0); 
    transform: translate3d(10px, 0, 0); 
    } 
} 

@keyframes shake { 
    0%, 100% { 
    -webkit-transform: translate3d(0, 0, 0); 
    transform: translate3d(0, 0, 0); 
    } 

    10%, 30%, 50%, 70%, 90% { 
    -webkit-transform: translate3d(-10px, 0, 0); 
    transform: translate3d(-10px, 0, 0); 
    } 

    20%, 40%, 60%, 80% { 
    -webkit-transform: translate3d(10px, 0, 0); 
    transform: translate3d(10px, 0, 0); 
    } 
} 

.shake { 
    -webkit-animation-name: shake; 
    animation-name: shake; 
} 
+0

葉,嘗試[.toggleClass()](http://jsfiddle.net/turbopipp/kzhx9ur4/) – turbopipp

+1

這是因爲沒有用戶界面重繪被稱爲類切換 –

回答

3

這是因爲removeClass和addClass發生這麼快就不允許DOM趕上每說。你可以做這樣的事情,如果你真的很討厭的setTimeout:

$("#passwordConfig").removeClass('shake animated').delay(50).queue(
    function (next) { 
     $(this).addClass('shake animated'); 
     next(); 
    } 
); 

http://jsfiddle.net/51dwhd2o/

切換類是也沒關係,但看起來它只會工作撥動的所有其他調用。

+1

沒有必要推遲,只是迫使UI重繪在某些之間切換類之間的方式,例如http://jsfiddle.net/51dwhd2o/1/我不能在Chrome瀏覽器以外的其他瀏覽器上測試它,但Webkit瀏覽器是衆所周知的優化用戶界面重新繪製,有時太多,因爲它似乎是這裏的情況 –

+1

哦,很酷,我不知道這會工作。在回答時學到了一些東西!總是很棒。謝謝!雖然在jQuery 3.0中不認爲沒有提供某種時間就可以工作。我知道他們進行了大規模的改變,以隱藏最新版本的節目。 – AtheistP3ace

+1

jq 3.x上的Ya(和1.x,因爲我可以測試它)需要'.hide()。show(0)'或者其他更好的方式,我不知道要強制ui重新繪製 –