CSS - 使用动画方向和动画填充模式共享@Keyframes规则集?

The*_*978 5 javascript css animation

我有一个简单的蓝色方块,我想控制2个按钮,"向左移动""向右移动".

  • 向左移动: 应将蓝色方块从右向左移动,将不透明度从0.5淡化为1并保留动画的最后一帧.

  • 向右移动: 应将蓝色方块从左向右移动,将不透明度从1淡化为0.5并保留动画的最后一帧.

我想分享一个@keyframes move规则集,但我对如何animation-directionanimation-fill-mode应该一起工作感到困惑.

第一次触发动画是正确的,无论动画是向左还是向右移动,但在此之后它不再按照应有的方式动画.

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");
})
Run Code Online (Sandbox Code Playgroud)
#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;}
 }
Run Code Online (Sandbox Code Playgroud)
<input type="button" id="left" value="MOVE LEFT">
<input type="button" id="right" value="MOVE RIGHT">

<div id="square"></div>
Run Code Online (Sandbox Code Playgroud)

Mic*_*ker 2

您可以使用 不使用动画来完成此操作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");
})
Run Code Online (Sandbox Code Playgroud)
#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;
 }
Run Code Online (Sandbox Code Playgroud)
<input type="button" id="left" value="MOVE LEFT">
<input type="button" id="right" value="MOVE RIGHT">

<div id="square"></div>
Run Code Online (Sandbox Code Playgroud)