我有一个用作三态复选框的元素。每当状态发生变化时,我想在该元素上运行动画。本质上,元素开始时没有附加任何类来指示第一个状态。然后我为一个状态添加一个类,然后删除该类并为第二个状态添加一个不同的类。
它在第一次点击时有效,但在后续点击时不播放动画。这是我到目前为止所拥有的:
$('button').click(function() {
var $div = $('div');
if (!$div.hasClass('is-colored')) {
$div.addClass('green is-colored');
} else {
$div.toggleClass('green red');
}
});
@keyframes Animation {
from {
opacity: 0;
transform: scaleX(0) scaleY(0);
}
to {
opacity: 1;
transform: scaleX(1) scaleY(1);
}
}
.green {
background-color: #0F0;
-webkit-animation: Animation 0.25s linear forwards;
-moz-animation: Animation 0.25s linear forwards;
animation: Animation 0.25s linear forwards;
}
.red {
background-color: #F00;
/* I tried applying the animation on the second state but this isn't working */
-webkit-animation: Animation 0.25s linear forwards;
-moz-animation: Animation 0.25s linear forwards;
animation: Animation 0.25s linear forwards;
}
div {
width: 100px;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<button>Change Color</button>
I know it's possible to restart an animation with JavaScript截至 3 年前,这似乎是不可能的 to do this without JavaScript.
简而言之,是否可以仅使用 CSS 和切换类(即不需要超时)在同一元素上多次执行相同的动画?
最佳答案
发生的事情是因为状态永远不会重置,所以动画不会再次启动。您要做的是在重置时删除颜色类,“等待”(0 秒)然后让新类为动画启动。
绿色的变化是这样的,完整变化见下文:
$div.removeClass('green');
setTimeout(function() {
$div.addClass('red');
}, 0);
编辑:在没有 javascript 延迟的情况下执行此操作。唯一的方法是创建另一个版本的动画,以便它不断运行不同的动画:
$('button').click(function() {
var $div = $('div');
if (!$div.hasClass('is-colored')) {
$div.addClass('green is-colored');
} else {
$div.toggleClass('green red');
}
});
@keyframes Animation {
from {
opacity: 0;
transform: scaleX(0) scaleY(0);
}
to {
opacity: 1;
transform: scaleX(1) scaleY(1);
}
}
@keyframes Animation2 {
from {
opacity: 0;
transform: scaleX(0) scaleY(0);
}
to {
opacity: 1;
transform: scaleX(1) scaleY(1);
}
}
.green {
background-color: #0F0;
-webkit-animation: Animation 0.25s linear forwards;
-moz-animation: Animation 0.25s linear forwards;
animation: Animation 0.25s linear forwards;
}
.red {
background-color: #F00;
/* I tried applying the animation on the second state but this isn't working */
-webkit-animation: Animation2 0.25s linear forwards;
-moz-animation: Animation2 0.25s linear forwards;
animation: Animation2 0.25s linear forwards;
}
div {
width: 100px;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<button>Change Color</button>
关于css - 如何在没有 JavaScript 的情况下切换类时运行相同的动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38018983/