Animation: persist() 方法
Web Animations API 的 Animation 介面的 persist() 方法顯式地使動畫持久化,防止它在被另一個動畫替換時被 自動移除。
語法
js
persist()
引數
無。
返回值
無(undefined)。
示例
使用 persist()
在此示例中,我們有三個按鈕
-
“新增持久化動畫”和“新增瞬態動畫”都會向紅色方塊新增一個新的 transform 動畫。動畫方向交替:第一個從左到右,第二個從右到左,依此類推。“新增持久化動畫”會對其建立的動畫呼叫
persist()。 -
第三個按鈕“取消動畫”將取消最近新增的動畫。
該示例顯示了一個列表,其中包含所有未被取消的動畫,按照新增的順序排列,以及每個動畫的 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();
}
結果
請注意,新增新的瞬態動畫會替換任何先前新增的瞬態動畫。這些動畫將被自動移除,它們的 replaceState 將是 "removed"。然而,持久化動畫不會被移除。
另請注意,已移除的動畫不會影響顯示;<div> 的位置由最近一個活動的或已持久化的動畫決定。
規範
| 規範 |
|---|
| Web 動畫 # dom-animation-persist |
瀏覽器相容性
載入中…
另見
- Web Animations API
- 用於控制網頁動畫的其他方法和屬性的
Animation。 Animation.replaceStateremove事件