4
我有一个简单的蓝色方块,我想控制2个按钮,“向左移动”和“向右移动”。CSS - 共享@Keyframes规则集与动画方向和动画 - 填充模式?
左移:应该从右侧移动蓝色正方形到左边,褪色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>
谢谢您的回答。但是,如果我有更复杂的动画,需要使用'animation'而不是'transition',我想知道如何共享'@keyframes'规则集。例如,如果蓝色方块的初始不透明度为0,则按下“向左移动”仍应该使用动画的“到/从”或“0%50%100%”来为广场制作动画。 – TheDarkIn1978
@ TheDark1978欢迎您。我不确定动画为什么不起作用。我可以继续看着它。你是否希望我删除这个答案,因为它“没有用处”,或者将它留作替代方法,以供将来发现此问题的任何人使用? –
不要删除答案,我确信其他人可能会觉得它有用。但是,如果您找到解决方案,请编辑您的答案。 – TheDarkIn1978