Animation:play() 方法

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since March 2020.

Web 动画 APIAnimation 接口的 play() 方法可开始或恢复动画的播放。如果动画结束,调用 play() 则会重新开始动画,从头开始播放。

语法

js
play()

参数

无。

返回值

无(undefined)。

示例

Alice 的成长游戏示例中,单击或轻触蛋糕会导致 Alice 长大的动画(aliceChange)向前播放,从而使她的体型变大并触发蛋糕的动画。包含两个 Animation.play() 和一个 EventListener

js
// 蛋糕有它自己的动画:
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,
    },
  );

// 暂停蛋糕的动画,以避免动画立即播放。
nommingCake.pause();

// 该函数会在用户点击或轻触时触发
const growAlice = () => {
  // 播放 Alice 的动画。
  aliceChange.play();

  // 播放蛋糕的动画。
  nommingCake.play();
};

// 当用户保持鼠标按下或轻触的状态时,调用 growAlice 来播放所有动画。
cake.addEventListener("mousedown", growAlice, false);
cake.addEventListener("touchstart", growAlice, false);

规范

Specification
Web Animations
# dom-animation-play

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
play

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

参见