Animation: phương thức persist()

Baseline Widely available

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

Phương thức persist() của giao diện Animation trong Web Animations API lưu giữ hoạt ảnh một cách tường minh, ngăn nó bị tự động loại bỏ khi bị thay thế bởi một hoạt ảnh khác.

Cú pháp

js
persist()

Tham số

Không có.

Giá trị trả về

Không có (undefined).

Ví dụ

Sử dụng persist()

Trong ví dụ này, chúng ta có ba nút:

  • "Add persistent animation" và "Add transient animation" mỗi nút thêm một hoạt ảnh biến đổi mới vào hình vuông đỏ. Các hoạt ảnh luân phiên đổi hướng: vì vậy hoạt ảnh đầu tiên đi từ trái sang phải, hoạt ảnh thứ hai đi từ phải sang trái, v.v. "Add persistent animation" gọi persist() trên hoạt ảnh mà nó tạo ra.

  • Nút thứ ba, "Cancel an animation", hủy hoạt ảnh được thêm gần đây nhất.

Ví dụ hiển thị danh sách tất cả hoạt ảnh chưa bị hủy, theo đúng thứ tự chúng được thêm vào, cùng với replaceState của từng hoạt ảnh.

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();
}

Kết quả

Lưu ý rằng việc thêm một hoạt ảnh tạm thời mới sẽ thay thế mọi hoạt ảnh tạm thời đã thêm trước đó. Những hoạt ảnh đó sẽ bị tự động loại bỏ, và replaceState của chúng sẽ là "removed". Tuy nhiên, các hoạt ảnh được lưu giữ sẽ không bị loại bỏ.

Cũng lưu ý rằng các hoạt ảnh đã bị loại bỏ không ảnh hưởng tới phần hiển thị; vị trí của <div> được xác định bởi hoạt ảnh đang hoạt động hoặc đã được lưu giữ gần đây nhất.

Thông số kỹ thuật

Specification
Web Animations
# dom-animation-persist

Tương thích trình duyệt

Xem thêm