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

瀏覽器相容性

另見