发现,如果我不让动画结束,则重置事件并更改动画,它不会取代前一个事件,而是将前一个事件与当前事件一起触发。
是否有阻止这种情况发生的方法?
原来,我什至不必更改动画。如果我只添加一个新的事件处理程序,它将只是排队。
该示例将允许您按下2个按钮来更改动画。每次更改动画时,都会生成一个新的动画事件,该事件也将递增并通过计数器。当您允许动画结束时,它将按照给定的顺序触发每个事件,这可以通过显示的消息看到。
function swap_animation(node, from, to) {
if (!$(node).hasClass(from)) {
node.classList.remove(from);
animated_callback(node, get_counter());
void node.offsetWidth;
node.classList.add(to);
} else {
animated_callback(node, get_counter());
}
}
function get_counter() {
let value = parseInt($("#counter").text()) + 1;
$("#counter").text(value);
return value;
}
function grow() {
let node = document.getElementById("item");
swap_animation(node, "shrink", "grow");
}
function shrink() {
let node = document.getElementById("item");
swap_animation(node, "grow", "shrink");
}
function animated_callback(node, counter)
{
$(node)
.one("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd",
function(e){
log("done event: " + counter + "\n");
});
}
function log(x) { $("#log").append(x); }
.grow {
animation-name: title-min;
animation-duration: 2s;
animation-timing-function: linear;
animation-fill-mode: forwards;
transform-origin: 0% 100% 0;
}
.shrink {
animation-name: title-min;
animation-duration: 1s;
animation-timing-function: linear;
animation-direction: reverse;
animation-fill-mode: forwards;
transform-origin: 0% 100% 0;
}
@keyframes title-min
{
from { transform: scale(0.5); }
to { transform: scale(1.0); }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<button onclick="grow()">Eat me! </button>
<button onclick="shrink()">Drink me! </button>
<h1 id="item">Alice </h1>
<p>Counter: <span id="counter">0</span></p>
<pre id="log"></pre>
</body>