Animation:pause() 方法

Baseline 已广泛支持

此功能已经成熟,并可在许多设备和浏览器版本上使用。自 ⁨2020 年 3 月⁩起,它已在各浏览器中推出。

Web Animations API 的 Animation 接口的 pause() 方法会暂停动画的播放。

语法

js
pause()

参数

无。

返回值

无。

异常

InvalidStateError DOMException

如果在动画的 currentTime 未解析(可能尚未开始播放),并且动画的结束时间为正无穷大,则会抛出此错误。

示例

Animation.pause() 在 Alice in Web Animations API Land 的 Growing/Shrinking Alice Game 中被多次使用,这主要是因为使用 Element.animate() 方法创建的动画会立即开始播放,如果您想避免这种情况,则必须手动暂停它们。

js
// animation of the cupcake slowly getting eaten up
const nommingCake = document
  .getElementById("eat-me_sprite")
  .animate(
    [{ transform: "translateY(0)" }, { transform: "translateY(-80%)" }],
    {
      fill: "forwards",
      easing: "steps(4, end)",
      duration: aliceChange.effect.timing.duration / 2,
    },
  );

// doesn't actually need to be eaten until a click event, so pause it initially:
nommingCake.pause();

此外,在重置时

js
// An all-purpose function to pause the animations on Alice, the cupcake, and the bottle that reads "drink me."
const stopPlayingAlice = () => {
  aliceChange.pause();
  nommingCake.pause();
  drinking.pause();
};

// When the user releases the cupcake or the bottle, pause the animations.
cake.addEventListener("mouseup", stopPlayingAlice);
bottle.addEventListener("mouseup", stopPlayingAlice);

规范

规范
Web 动画
# dom-animation-pause

浏览器兼容性

另见