我正在尝试将对象的动画重置为其初始点,以便可以从头开始重新启动。
function swap_animation(node, from, to) {
let t = node.style.animationDuration;
node.style.animationDuration = "0s";
node.style.animationPlayState = "initial";
setTimeout(function(){
node.style.animationDuration = t;
node.classList.remove(from);
node.classList.add(to);
}, 10);
}
function grow() {
let node = document.getElementById("item");
swap_animation(node, "shrink", "grow");
}
function shrink() {
let node = document.getElementById("item");
swap_animation(node, "grow", "shrink");
}
.grow {
animation-name: title-min;
animation-duration: 10s;
animation-timing-function: linear;
animation-fill-mode: forwards;
transform-origin: 0% 100% 0;
}
.shrink {
animation-name: title-min;
animation-duration: 10s;
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); }
}
<body>
<button onclick="grow()">Eat me! </button>
<button onclick="shrink()">Drink me! </button>
<h1 id="item">Alice </h1>
</body>
该示例显示,如果您在 Eat me!和 Drink me!之间单击,则Alice会在10秒内增长和收缩。但是,如果在两者之间切换,则会注意到动画从切换前的位置继续播放。
我想我在某处读到一种实现此目的的方法是克隆对象并将旧对象替换为新对象。这似乎真的很过分,我认为这可能会导致性能问题,如果对象很大,更是如此,并且也很糟糕,因为它可能导致内存碎片。
必须有某种方法来保留对象并修改其属性以解决此问题,不是吗?
答案 0 :(得分:0)
好的,我找到了答案。这是为了触发重排。从this site得到了答案。不确定void
在做什么。
function swap_animation(node, from, to) {
node.classList.remove(from);
void node.offsetWidth;
node.classList.add(to);
}
function grow() {
let node = document.getElementById("item");
swap_animation(node, "shrink", "grow");
}
function shrink() {
let node = document.getElementById("item");
swap_animation(node, "grow", "shrink");
}
.grow {
animation-name: title-min;
animation-duration: 10s;
animation-timing-function: linear;
animation-fill-mode: forwards;
transform-origin: 0% 100% 0;
}
.shrink {
animation-name: title-min;
animation-duration: 10s;
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); }
}
<body>
<button onclick="grow()">Eat me! </button>
<button onclick="shrink()">Drink me! </button>
<h1 id="item">Alice </h1>
</body>