这是一个简单的问题,但我对编程还很陌生,我不太确定如何做到这一点。
我有一个在按下按钮时移动的 div
var checkbox = document.getElementById('checkbox');
var box = document.getElementById('box');
box.addEventListener('click', function() {
checkbox.checked = true;
});
#box {
position: absolute;
transform: translate3d(0, 0, 0);
height: 20%;
width: 20%;
background-color: red;
}
@keyframes moveRight {
0% {
transform: translate3d(0, 0, 0);
}
60% {
transform: translate3d(120%, 0, 0);
}
100% {
transform: translate3d(100%, 0, 0);
}
}
#checkbox:checked ~ #box {
animation-name: moveRight;
animation-duration: 1s;
animation-fill-mode: forwards;
}
<!DOCTYPE html>
<html>
<body>
<input type="checkbox" id="checkbox" />
<div id="box">
</div>
</body>
</html>
这是一个简单的动画,因此对于这种情况来说,这样做并不是真正的问题。问题是当我想通过复选框添加另一个动画时,它会看到两个复选框都被“选中”并且它会运行两个动画。使用 javascript 并且没有复选框,我该如何执行以下操作:
-添加CSS动画 - 当我想使用其他动画时将其删除
谢谢!
最佳答案
例如,这可以通过添加/删除框元素的 css 类来完成。 (如果我正确理解你的问题)
var button1 = document.getElementById('button1');
var button2 = document.getElementById('button2');
var box1 = document.getElementById('box1');
button1.addEventListener('click', function() {
box1.className = "";
box1.className += " moving-box-right";
});
button2.addEventListener('click', function() {
box1.className = "";
box1.className += " moving-box-left";
});
#box1 {
position: absolute;
transform: translate3d(0, 0, 0);
height: 20%;
width: 20%;
background-color: red;
}
@keyframes moveRight {
0% {
transform: translate3d(0, 0, 0);
}
60% {
transform: translate3d(120%, 0, 0);
}
100% {
transform: translate3d(100%, 0, 0);
}
}
@keyframes moveLeft {
0% {
transform: translate3d(100%, 0, 0);
}
100% {
transform: translate3d(0%, 0, 0);
}
}
.moving-box-right {
animation-name: moveRight;
animation-duration: 1s;
animation-fill-mode: forwards;
}
.moving-box-left {
animation-name: moveLeft;
animation-duration: 1s;
animation-fill-mode: forwards;
}
<!DOCTYPE html>
<html>
<body>
<button id="button1">Move box right</button>
<button id="button2">Move box left</button>
<div id="box1"></div>
</body>
</html>
关于javascript - 使用 javascript 操作 CSS 动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35352430/