Animation: play() 方法

Baseline 已廣泛支援

此功能已經成熟,並可在許多裝置和瀏覽器版本上使用。自 ⁨2020 年 3 月⁩起,它已在各瀏覽器中推出。

play() 方法是 Web Animations APIAnimation 介面的一部分,用於開始或恢復動畫的播放。如果動畫已經完成,呼叫 play() 將會從頭重新開始播放動畫。

語法

js
play()

引數

無。

返回值

無(undefined)。

示例

Growing/Shrinking Alice Game 示例中,點選或輕觸蛋糕會觸發愛麗絲的變大動畫 (aliceChange) 正向播放,使她變大,同時也會觸發蛋糕的動畫。這需要呼叫兩個 Animation.play(),在一個 EventListener 中實現。

js
// The cake has its own animation:
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,
    },
  );

// Pause the cake's animation so it doesn't play immediately.
nommingCake.pause();

// This function will play when ever a user clicks or taps
const growAlice = () => {
  // Play Alice's animation.
  aliceChange.play();

  // Play the cake's animation.
  nommingCake.play();
};

// When a user holds their mouse down or taps, call growAlice to make all the animations play.
cake.addEventListener("mousedown", growAlice);
cake.addEventListener("touchstart", growAlice);

規範

規範
Web 動畫
# dom-animation-play

瀏覽器相容性

另見