簡體   English   中英

CSS動畫前進然后向后閃爍

[英]CSS Animation Forward then Backward Flickering

我正在嘗試創建一個CSS動畫,當用戶單擊一個元素時,它會向右動畫,然后當它們再次單擊它時,它會動畫到左側。 我遇到的問題是它引入了閃爍。 我知道原因,但我不確定解決問題的最佳方法。 我想要這個問題最優雅的解決方案。

我在這里設置了一個jsFiddle(僅限WebKit): http//jsfiddle.net/4Ad5c/2/

CSS:

.animateRight{
    -webkit-animation: goRightLeft 1s;
    -webkit-animation-fill-mode: forwards;
}
.animateLeft{
    -webkit-animation: goRightLeft 1s;
    -webkit-animation-fill-mode: backwards;
    -webkit-animation-direction: reverse;    
}
@-webkit-keyframes goRightLeft {
    0%{margin-left: 0px;}
    100%{margin-left: 100px;}
}

JavaScript:

this.animateBox = function(className){
    var box = document.getElementsByClassName('box')[0];
    box.className = "box";
    setTimeout(function(){
        box.className = "box " + className;
    },1);
};

當您單擊Animate Right時,它按預期工作,但是當您單擊Animate Left時,它將向左閃爍,然后按預期動畫。 原因是你必須刪除該類並添加另一個以使動畫再次運行,但我不知道讓它工作的最佳方法。 我想我可以在刪除以前的動畫時添加一個類,但是這對我來說似乎不對。

謝謝您的幫助!

閃爍的原因:

您在設置下一個animationClass之前在點擊上應用了類box ,這使得框突然向左移動。 然后你應用動畫反轉。 因此它會導致閃爍,同時它的殘骸向左移動(刪除類)並在超時中添加類會導致根據animateLeft類中的fillmode和方向animateLeft動畫並使其更加goRightLeft ,因為goRightLeft再次添加邊距將其拉到右邊緣在規則和webkit-animation-fill-mode: backwards; 推到左邊。 所以我在這里提到的一種方法是反向(增加/減少)邊際。

這是一個解決方案:

對於真正的反向動畫,您需要像前進動畫一樣將邊距減少從100px應用到0。 所以只需為LeftToRight添加keyframes並將其應用於動畫中。

CSS

.animateRight{
    -webkit-animation: goRightLeft 1s;
    -webkit-animation-fill-mode: forwards;
}
.animateLeft{
    -webkit-animation: goLeftRight 1s; /* Note the goLeftRight animation */
      -webkit-animation-fill-mode: backwards;


}
@-webkit-keyframes goRightLeft {
    0%{margin-left: 0px;}
    100%{margin-left: 100px;}
}

@-webkit-keyframes goLeftRight { /* Note the new keyframes rule for reverse animation*/
    0%{margin-left: 100px;}
    100%{margin-left: 0px;}
}

腳本

this.animateBox = function(className){
    var box = document.getElementsByClassName('box')[0];
    box.className = "box " + className;

};

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM