CSS animation forward and then reverse flicker

I'm trying to create a CSS animation when a user clicks on an element that he animates on the right, and then when he clicks on it again, he animates to the left. The problem is that it starts to flicker. I know the reason, but I'm not sure if this is the best way to fix it. I want the most elegant solution to this problem.

I install jsFiddle (WebKit only) here: 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); }; 

When you click the Animation Right button, it works as expected, but when you click the Animation Left button, it flickers to the left and then animates as expected. The reason is that you need to remove the class and add another to animate the animation, but I don't know how best to do it. I believe that I could add a class when deleting a previous animation that has it in its current state, but that seems wrong to me.

Thanks for the help!

+4
source share
1 answer

Flicker Reason:

You apply the box class when you click before setting the next animation class, which makes the window left to left. and then you use the animation to go back. Thus, it causes flickering while the interruption continues (class deletion), and adding a class in timeout causes revereses animation according to fillmode mode and direction in animateLeft class and makes it even harder as goRightLeft again adds a marker which pulls it to the right due to the field in the rule and webkit-animation-fill-mode: backwards; pushed left. Therefore, one of the approaches that I mentioned here is to do the opposite (add / decrease) fields.

Here is one solution for this:

For real reverse animation, you need to apply the difference from 100px to 0, as during the animation forward. So just add keyframes for LeftToRight and apply this in the animation.

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;} } 

Script

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

Demo

+4
source

Source: https://habr.com/ru/post/1484731/


All Articles