我有一个简单的蓝色方块,我想用2个按钮控制,"向左移动" 和"向右移动"
向左移动:应将蓝色方块从右向左移动,将不透明度从0.5淡化为1并保留动画的最后一帧。
向右移动:应将蓝色方块从左向右移动,将不透明度从1淡化为0.5并保留动画的最后一帧。
我想分享一个@keyframes move
规则集,但我对animation-direction
和animation-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;
答案 0 :(得分: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");
})
&#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;