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事件