我有一个 CSS 动画,根据某些情况,我希望能够根据某些 JS 随时向前或向后切换。这是一个基本示例:
html
<div id="box"></div>
<button onclick="toggle()">toggle</button>
js
window.isSmall = true;
window.toggle = function() {
if (isSmall) {
var el = document.getElementById("box");
el.classList.add("bigger");
} else {
// ????
}
isSmall = !isSmall;
}
CSS
@keyframes bigger {
from { width:100px; height:100px; }
to { width:200px; height:200px; }
}
#box {
width:100px;
height:100px;
background-color: red;
}
.bigger {
animation-name: bigger;
animation-duration: 1s;
animation-fill-mode: forwards;
}
fiddle : http://jsfiddle.net/gbh408up/
我认为这会非常简单,但令人惊讶的是我无法找到实现此目的的方法。请注意,我专门寻找带有动画而不是过渡的解决方案。有什么想法吗?
最佳答案
您可以使用 2 个类来制作所需的动画。
window.isSmall = true;
window.toggle = () => {
const box = document.getElementById("box");
if (isSmall) {
box.classList.remove("smaller");
box.classList.add("bigger");
} else {
box.classList.remove("bigger");
box.classList.add("smaller");
}
isSmall = !isSmall;
console.log(isSmall)
}
@keyframes bigger {
from {
width: 100px;
height: 100px;
}
to {
width: 200px;
height: 200px;
}
}
@keyframes smaller {
from {
width: 200px;
height: 200px;
}
to {
width: 100px;
height: 100px;
}
}
#box {
width: 100px;
height: 100px;
background-color: red;
}
.bigger {
animation-name: bigger;
animation-duration: 1s;
animation-fill-mode: forwards;
}
.smaller {
animation-name: smaller;
animation-duration: 1s;
animation-fill-mode: forwards;
}
<div id="box"></div>
<button onclick="toggle()">toggle</button>
关于javascript - 如何使CSS动画按需向前或向后播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52085536/