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

时间:2017-06-23 23:19:15

标签: 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");
})

#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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

您可以使用transition在没有动画的情况下执行此操作。

&#13;
&#13;
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");
})
&#13;
#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;
 }
&#13;
<input type="button" id="left" value="MOVE LEFT">
<input type="button" id="right" value="MOVE RIGHT">

<div id="square"></div>
&#13;
&#13;
&#13;