问题:
I have a css animation that depending on some situation I want to be able to toggle forwards or backwards at any time based on some JS. Heres a basic example:
html
<...
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
I have a css animation that depending on some situation I want to be able to toggle forwards or backwards at any time based on some JS. Heres a basic example:
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/
I thought this would be pretty straight-forward but surprisingly I wasn't able to find a method to accomplish this. Note, I'm specifically looking for a solution with animations, NOT transitions. Any ideas?
回答1:
You can work with 2 classes that animate what is required.
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>
回答2:
I just finished figuring this out. So here is my solution:
<div id="box"></div>
<button onclick="toggle()">toggle</button>
window.isSmall = true;
window.toggle = function() {
var el = document.getElementById("box");
if (el.className == "a") {
el.className = "b";
} else {
el.className = "a";
}
isSmall = !isSmall;
console.log('toggle');
}
@keyframes a {
from { width:100px; height:100px; }
to { width:200px; height:200px; }
}
@keyframes b {
from { width:200px; height:200px; }
to { width:100px; height:100px; }
}
#box {
width:100px;
height:100px;
background-color: red;
}
.a {
animation-name: a;
animation-duration: 1s;
animation-fill-mode: forwards;
}
.b {
animation-name: b;
animation-duration: 1s;
animation-fill-mode: forwards;
}
I changed the "bigger" to just "a" and my "smaller" to just "b". But this works. Ok - I have it in a fiddle now.
https://jsfiddle.net/markem/2b6n3gmc/1/
Also, this was somewhat answered with this question here on StackOverflow:
Javascript simple add class remove class