Animation: remove 事件

Baseline 已廣泛支援

此特性已經十分成熟,可在許多裝置和瀏覽器版本上使用。自 2020 年 7 月以來,它已在各大瀏覽器中可用。

當動畫被瀏覽器自動移除時,會觸發 Animation 介面的 remove 事件。

語法

在諸如 addEventListener() 之類的方法中使用事件名稱,或設定事件處理程式屬性。

js
addEventListener("remove", (event) => { })

onremove = (event) => { }

事件型別

一個 AnimationPlaybackEvent 物件。繼承自 Event

Event AnimationPlaybackEvent

事件屬性

除了下面列出的屬性之外,父介面 Event 的屬性也可使用。

AnimationPlaybackEvent.currentTime 只讀

生成事件的動畫的當前時間。

AnimationPlaybackEvent.timelineTime 只讀

生成事件的動畫的時間線時間值。

示例

移除被替換的動畫

在此示例中,我們有一個 <button id="start"> 元素,以及一個在滑鼠移動時執行的事件監聽器。<a href="/en-US/docs/Web/API/Element/mousemove_event" title="mousemove">mousemove 事件處理程式會設定一個動畫,該動畫會將 <button> 元素動畫到滑鼠指標的位置。這可能會導致動畫列表非常龐大,從而引起記憶體洩漏。出於這個原因,現代瀏覽器會自動移除被其他動畫覆蓋的前向填充動畫。

將顯示建立的動畫數量。remove 事件監聽器用於計數並顯示被移除的動畫數量。

所有動畫(除一個外)最終都應該被移除。

HTML

html
<button id="start">Click to drag</button>
<br />
<button id="reset">Reset example</button>
<p>
  Click the button to start the animation (disabled by default to protect those
  who suffer migraines when experiencing such animations).
</p>
<p>Animations created: <span id="count-created">0</span></p>
<p>Animations removed: <span id="count-removed">0</span></p>

CSS

css
:root,
body {
  margin: 0;
  padding: 0;
  height: 100%;
}

button {
  margin: 0.5rem 0;
}

JavaScript

js
const button = document.querySelector("#start");
let created = 0;
let removed = 0;

button.addEventListener(
  "click",
  () => {
    document.body.addEventListener("mousemove", (event) => {
      const animation = button.animate(
        { transform: `translate(${event.clientX}px, ${event.clientY}px)` },
        { duration: 500, fill: "forwards" },
      );
      created++;
      showCounts();

      // the remove event fires after the animation is removed
      animation.addEventListener("remove", () => {
        removed++;
        showCounts();
      });
    });
  },
  { once: true },
);

function showCounts() {
  document.getElementById("count-created").textContent = created;
  document.getElementById("count-removed").textContent = removed;
}

const reset = document.querySelector("#reset");
reset.addEventListener("click", () => {
  document.location.reload();
});

結果

規範

規範
Web 動畫
# dom-animation-onremove
Web 動畫
# remove-event

瀏覽器相容性

另見