Animation: overallProgress 屬性

overallProgressAnimation 介面的一個只讀屬性,它返回一個介於 01 之間的數字,表示動畫在其完成狀態下的總體進度。這是動畫所有迭代的總進度,而不是單個迭代的進度。

overallProgress 在所有動畫中都具有一致的行為,與 timeline 的型別無關。

一個介於 01 之間的數字,如果動畫沒有時間軸、不活躍、尚未播放,或者其 currentTime 被設定為非時間值,則返回 null

如果動畫的 iterations 屬性設定為 Infinity,或者其 currentTime 被設定為負值,overallProgress 將返回 0

如果動畫的 duration 設定為 0overallProgress 將返回 1

示例

顯示進度百分比

此演示使用 overallProgress 來建立“進度百分比”讀數,並在動畫執行時將其顯示在螢幕上。

HTML

HTML 包含一個用於啟動動畫的 <button>,一個用於顯示進度百分比的 <p> 元素,以及一個將要被動畫化的 <div>

html
<button>Run animation</button>
<p class="progress">Progress: 0%</p>
<div class="box"></div>

演示的 CSS 提供了一些基本的樣式,這些樣式對於理解 JavaScript 的工作原理並不重要,因此為了簡潔起見,我們將其隱藏了。

JavaScript

在 JavaScript 中,我們首先獲取對 <button><p><div> 元素的引用。

然後我們建立

  • 一個 animation 變數,它將引用動畫,一旦我們建立了它。
  • 一個 關鍵幀 陣列
  • 一個包含時間屬性的選項物件。
js
const btn = document.querySelector("button");
const progress = document.querySelector(".progress");
const box = document.querySelector(".box");

let animation;

const keyframes = [{ rotate: "0deg" }, { rotate: "360deg" }];

const timingProps = {
  duration: 3000,
  iterations: 1,
};

接下來,我們透過 addEventListener()<button> 新增一個 "click" 事件監聽器,以便在按下按鈕時:

  1. 使用 Element.animate() 啟動動畫,傳入之前定義的關鍵幀和選項,並將返回的 Animation 例項賦值給 animation 變數。
  2. 透過 requestAnimationFrame() 方法執行一個名為 updateProgress() 的函式,該函式負責更新進度百分比顯示。
js
btn.addEventListener("click", () => {
  // Animate the box
  animation = box.animate(keyframes, timingProps);
  // Start updating the progress percentage via rAF()
  requestAnimationFrame(updateProgress);
});

現在,我們來定義 updateProgress() 函式。它會查詢 Animation.playState 來檢查動畫是否未完成。如果未完成,我們獲取 overallProgress 的當前值,將其乘以 100 並向下取整,將其轉換為一個完整的百分比數字,然後用它更新 <p> 元素的 textContent 值。然後,我們再次呼叫 requestAnimationFrame(updateProgress) 來重新執行進度百分比更新。

如果動畫已完成,我們用“Finished!”訊息替換進度百分比,並且不呼叫 requestAnimationFrame(updateProgress),因此進度百分比更新將停止。

js
function updateProgress() {
  // Check if the animation is finished
  if (animation.playState !== "finished") {
    // Convert overallProgress to a whole number percentage
    const progressPercentage = Math.floor(animation.overallProgress * 100);
    // Update the progress paragraph with the percentage
    progress.textContent = `Progress: ${progressPercentage}%`;
    // Only request the next frame if the animation is not finished
    requestAnimationFrame(updateProgress);
  } else {
    progress.textContent = "Finished!";
  }
}

結果

輸出看起來像這樣。嘗試按下按鈕,觀看動畫和相關的進度指示器執行。

規範

規範
Web 動畫 Level 2
# dom-animation-overallprogress

瀏覽器相容性

另見