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

浏览器兼容性

另见