CSS - Sharing @Keyframes settings with animation mode and fill animation?

I have a simple blue square that I want to control using two buttons: "Move Left" and "Move Right".

  • Move Left: . Move the blue square from right to left, reduce the transparency from 0.5 to 1 and save the last frame of the animation.

  • Right the Move: . Move the blue square from left to right, reduce the transparency from 1 to 0.5 and save the last frame of the animation.

I want to share one set of rules @keyframes move, but I'm confused about how animation-directionand animation-fill-modeshould work together.

When you start the animation for the first time, whether the animation moves left or right correctly, but after that it no longer animates as it should.

const square = document.getElementById("square");

const leftButton = document.getElementById("left");
leftButton.addEventListener("click", () => {
    square.classList.remove("moveRight");
    square.classList.add("moveLeft");
});

const rightButton = document.getElementById("right")
rightButton.addEventListener("click", () => {
    square.classList.remove("moveLeft");
    square.classList.add("moveRight");
})
#square {
    width: 200px;
    height: 200px;
    background-color: blue;
    margin-top: 20px;
    position: relative;
}
 
 .moveLeft {
     animation: move 1s linear normal forwards;
 }
 
 .moveRight {
     animation: move 1s linear reverse forwards;
 }
 
 @keyframes move {
     from {left: 100px; opacity: 0.5;}
     to {left: 0; opacity 1;}
 }
<input type="button" id="left" value="MOVE LEFT">
<input type="button" id="right" value="MOVE RIGHT">

<div id="square"></div>
Run codeHide result
+4
1

, transition.

const square = document.getElementById("square");

const leftButton = document.getElementById("left");
leftButton.addEventListener("click", () => {
    square.classList.remove("moveRight");
    square.classList.add("moveLeft");
});

const rightButton = document.getElementById("right")
rightButton.addEventListener("click", () => {
    square.classList.remove("moveLeft");
    square.classList.add("moveRight");
})
#square {
    width: 200px;
    height: 200px;
    background-color: blue;
    margin-top: 20px;
    position: relative;
  transition: transform 1s, opacity 1s;
}
 
 .moveLeft {
   transform: translateX(0);
   opacity: 1;
 }
 
 .moveRight {
  transform: translateX(100px);
   opacity: .5;
 }
<input type="button" id="left" value="MOVE LEFT">
<input type="button" id="right" value="MOVE RIGHT">

<div id="square"></div>
Hide result
+1

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


All Articles