首页 > 解决方案 > 如何在不破坏原始标签对象的情况下停止和重置动画?

问题描述

我正在尝试将对象的动画重置为其初始点,以便我可以从头开始重新启动它。

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 秒内增长和缩小。但是,如果您在两者之间切换,您会注意到动画从切换前的位置继续播放。

我想我在某处读到,这样做的一种方法是克隆对象并用新对象替换旧对象。这似乎真的有点矫枉过正,我认为可能会导致性能问题,如果对象很大,更是如此,而且也会很糟糕,因为它会导致内存碎片。

必须有某种方法来保留对象并修改它的属性来解决这个问题,不是吗?

标签: javascriptjquerycss-animationskeyframe

解决方案


好的,我找到了答案。这是触发回流。从这个网站得到了答案。不完全确定那里在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>


推荐阅读