Animation: persist() メソッド
Baseline 2022
Newly available
Since September 2022, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.
persist()
はウェブアニメーション API の Animation
インターフェイスのメソッドで、アニメーションを明示的に維持し、 他のアニメーションに置き換わったときに自動的に削除されるのを防ぎます。
構文
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 |
ブラウザーの互換性
BCD tables only load in the browser
関連情報
- ウェブアニメーション API
Animation
: ウェブページのアニメーションを制御することができるその他のメソッドやプロパティAnimation.replaceState
remove
event