Animation: persist() メソッド

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.

persist()ウェブアニメーション APIAnimation インターフェイスのメソッドで、アニメーションを明示的に維持し、 他のアニメーションに置き換わったときに自動的に削除されるのを防ぎます。

構文

js
persist()

引数

なし。

返値

なし (undefined)。

persist() の使用

この例には、 3 つのボタンがあります。

  • "Add persistent animation" と "Add transient animation" はそれぞれ、赤い四角に新しい座標変換アニメーションを追加します。最初のアニメーションは左から右へ、 2 つ目は右から左へ、といった具合に、アニメーションは交互に向きを変えます。"Add persistent animation" は作成したアニメーションに persist() を呼び出します。

  • 3 つ目のボタン "Cancel an animation" は、最近追加したアニメーションを取り消される可能性があります。

この例では、キャンセルされる可能性のないすべてのアニメーションのリストが、追加された順に、それぞれのアニメーションの replaceState とともに表示されます。

HTML

html
<div id="animation-target"></div>
<button id="start-persistent">Add persistent animation</button>
<button id="start-transient">Add transient animation</button>
<button id="cancel">Cancel an animation</button>
<ol id="stack"></ol>

CSS

css
div {
  width: 100px;
  height: 100px;
  background: red;
  transform: translate(100px);
}

JavaScript

js
const target = document.getElementById("animation-target");
const persistentButton = document.getElementById("start-persistent");
const transientButton = document.getElementById("start-transient");
const cancelButton = document.getElementById("cancel");
persistentButton.addEventListener("click", () => startAnimation(true));
transientButton.addEventListener("click", () => startAnimation(false));
cancelButton.addEventListener("click", cancelTop);
const stack = [];

let offset = -100;

function startAnimation(persist) {
  offset = -offset;
  const animation = target.animate(
    { transform: `translate(${100 + offset}px)` },
    { duration: 500, fill: "forwards" },
  );
  stack.push(animation);
  if (persist) {
    animation.persist();
  }
  // Add the animation to the displayed stack (implementation not shown)
  show(animation, offset);
}

function cancelTop() {
  stack.pop()?.cancel();
}

結果

新しい transient アニメーションを追加すると、前回追加した transient アニメーションが置き換わることに注意してください。それらのアニメーションは自動的に除去され、 replaceState"removed" となります。しかし、 persistent アニメーションは除去されません。

<div> の位置は最新のアクティブまたは persistent アニメーションによって決定されます。

仕様書

Specification
Web Animations
# dom-animation-persist

ブラウザーの互換性

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
persist

Legend

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

Full support
Full support

関連情報