JavaScript - DOM 動畫



DOM 動畫可以透過使用 JavaScript 改變 DOM 元素的樣式來實現。當改變是漸進的並且時間間隔很小時,動畫看起來是連續的。通常,有三種方法可以動畫化 DOM 元素

  • 使用 CSS 過渡 - 它利用 CSS 中預定義的動畫樣式,這些樣式由元素屬性的變化觸發。

  • 使用 CSS 動畫 - 透過在 CSS 檔案中定義關鍵幀和動畫屬性,它提供了對動畫時間和行為的更多控制。

  • 使用 JavaScript - 它提供了最大的靈活性,允許你直接在 JavaScript 程式碼中動態操作樣式屬性並建立複雜的動畫。

本章提供了一個關於如何使用 JavaScript 動畫化 DOM 元素的基本理解。

使用 JavaScript 動畫化 DOM 元素

JavaScript 可用於更改 DOM 元素的樣式。

你可以在特定時間段後更改 DOM 元素的樣式以使其動起來。例如,你可以使用 setInterval() 方法來更改 DOM 元素的位置,使其透過動畫從一個位置移動到另一個位置。

同樣,你可以更新 CSS 屬性(如“animation”等)以動態地為元素設定動畫。

此外,requestAnimationFrame() 方法也可以用於為 DOM 元素設定動畫。

下面,你將學習不同的方法來為 DOM 元素設定動畫。

使用 setInterval() 方法為 DOM 元素設定動畫

你可以在每個時間段後呼叫 setInterval() 方法並更改 DOM 元素的樣式以使其動起來。但是,你可以將時間段保持較小以使動畫流暢執行。

語法

請遵循以下語法使用 setInterval() 方法為 DOM 元素設定動畫。

let id = setInterval(frame_func, timeframe);
function frame_func() {
    if (animation_end) {
        clearInterval(id);
    } else {
        // change style to animate
    }
}

在上面的語法中,我們使用 setInterval() 方法啟動動畫,並在每隔“timeframe”毫秒後呼叫 frame_func()。

在 frame_func() 函式中,我們定義了結束或繼續動畫的條件。

示例

在下面的程式碼中,我們為 <div> 元素設定了樣式。

當用戶點選按鈕時,它將呼叫 startAnimation() 函式。

在 startAnimation() 函式中,我們定義了“pos”變數並將其初始化為 0,表示 div 元素的初始位置。

之後,我們使用 setInterval() 方法在每隔 5 毫秒後呼叫 animationFrame() 函式。

在 animationFrame() 函式中,如果內部 div 的位置變為 350,我們將使用 clearInterval() 方法停止動畫。否則,我們將更改內部 div 的左側位置。

當你點選按鈕時,它將使內部 div 元素從左向右移動。

<!DOCTYPE html>
<html>
<head>
  <style>
    #parent {
      width: 700px;
      height: 50px;
      position: relative;
      background: yellow;
    }
    #child {
      width: 50px;
      height: 50px;
      position: absolute;
      background-color: red;
    }
  </style>
</head>
<body>
  <div id = "parent">
    <div id = "child"> </div>
  </div>
  <br>
  <button onclick = "startAnimation()"> Animate Div  </button>
  <script>
    function startAnimation() {
      const elem = document.getElementById("child");
      // Starting position
      let pos = 0;
      // Changing frames for animation
      let id = setInterval(animationFrame, 5);
      function animationFrame() {
        // Stop the animation
        if (pos == 350) {
          clearInterval(id);
        } else {
          pos++;
          elem.style.left = pos + "px";
        }
      }
    }
  </script>
</body>
</html>

示例

在下面的程式碼中,<div> 元素的背景顏色為綠色。

我們使用 `setInterval()` 方法每隔 50 毫秒呼叫一次 `animationFrame()` 函式。

在 `animationFrame()` 函式中,我們將 `

` 元素的不透明度更改 0.1。當不透明度小於或等於 0 時,我們使用 `clearInterval()` 方法停止動畫。

<!DOCTYPE html>
<html>
<head>
  <style>
    #parent {
      width: 700px;
      height: 200px;
      background: green;
    }
  </style>
</head>
<body>
  <div id = "parent">
  </div>
  <br>
  <button onclick = "startAnimation()"> Animate Div </button>
  <script>
    function startAnimation() {
      const parent = document.getElementById("parent");
      let opacity = 1;
      let id = setInterval(animationFrame, 50);
      function animationFrame() {
        if (opacity <= 0) {
          // Stop animation
          clearInterval(id);
          parent.style.opacity = 1;
          parent.style.backgroundColor = "red";
        } else {
          // Decrease the opacity
          parent.style.opacity = opacity;
          opacity = opacity - 0.1;
        }
      }
    }
  </script>
</body>
</html>

使用 `requestAnimationFrame()` 方法動畫化 DOM 元素

`requestAnimationFrame()` 方法用於像 `setInterval()` 方法一樣動畫化 DOM 元素。它連續執行任務並在瀏覽器中重繪下一幀。

`requestAnimationFrame()` 方法比 `setInterval()` 方法更有效率地進行渲染。

語法

遵循以下語法使用 `requestAnimationFrame()` 方法來動畫化 DOM 元素。

function animate() {
    // Animation logic
    // Request the next animation frame
    requestAnimationFrame(animate);
}
// Animation loop
animate();

讓我們瞭解 `requestAnimationFrame()` 方法的工作原理。

  • 您將回調函式作為 `requestAnimationFrame()` 方法的引數傳遞,以執行下一幀。

  • Web 瀏覽器將在重繪下一幀之前執行回撥函式。

  • 回撥函式將更新 DOM 元素。

  • 瀏覽器將重繪 DOM 元素。

  • 瀏覽器將再次呼叫回撥函式,迴圈將繼續。

您可以使用 `cancelAnimationFrame()` 方法取消動畫。

示例

在下面的程式碼中,我們定義了 `startAnimation()` 和 `stopAnimation()` 函式,並在使用者單擊按鈕時呼叫它們。

在 `startAnimation()` 函式中,我們將 'pos' 的值增加 1,並更新子 div 元素的左側位置。

之後,我們使用 `requestAnimationFrame()` 方法在 Web 瀏覽器中繪製下一幀。它將子 div 元素從父 div 元素的左側移動到右側。

`stopAnimation()` 函式使用 `cancelAnimationFrame()` 方法停止動畫。它將 `requestAnimationFrame()` 方法返回的 id 作為引數。

<!DOCTYPE html>
<html>
<head>
  <style>
    #parent {width: 700px; height: 50px; position: relative;background: yellow;}
    #child {width: 50px;height: 50px; position: absolute; background-color: red;}
  </style>
</head>
<body>
  <div id = "parent">
    <div id = "child"> </div>
  </div>
  <br>
  <button onclick = "startAnimation()"> Animate Div </button>
  <button onclick = "stopAnimation()"> Stop Animation </button>
  <script>
    let animationId;
    let pos = 0;
    function startAnimation() {
      const elem = document.getElementById("child");
      function animationFrame() {
        if (pos < 650) {
          pos++;
          elem.style.left = pos + "px";
          // Make a call for a next frame
          animationId = requestAnimationFrame(animationFrame);
        }
      }
      // Start Animation
      animationFrame();
    }

    function stopAnimation() {
      // Stop animation
      if (animationId) {
        cancelAnimationFrame(animationId);
        animationId = null;
      }
    }
  </script>
</body>
</html>

透過更改 CSS 屬性來動畫化 DOM 元素

CSS 的 `animation` 屬性可用於向 DOM 元素新增動畫。JavaScript 也允許自定義 `animation` 屬性。

語法

遵循以下語法透過在 JavaScript 中更改元素的 `animation` 屬性的值來動畫化 DOM 元素。

element.style.animation = "key_frame_name duration timing_function iterationCount";

屬性值

  • key_frame_name − 這是您需要在 CSS 中定義的關鍵幀的名稱。

  • duration − 這是動畫的持續時間。

  • timing_function − 用於設定動畫的執行方式。

  • iterationCount − 指定動畫應重複的次數。

示例

在下面的程式碼中,當用戶單擊按鈕時,我們呼叫 `animateDiv()` 函式並更新 div 元素的 style 物件的 `animation` 屬性的值。

我們已經在 CSS 中定義了 `moveAnimation` 關鍵幀。因此,當您單擊按鈕時,它將開始移動 div 元素。

<!DOCTYPE html>
<html>
<head>
  <style>
    #element {
      width: 90px;
      height: 90px;
      background: blue;
      color: white;
      position: relative;
      text-align: center;
    }
    @keyframes moveAnimation {
      from {
        transform: translateX(0);
      }
      to {
        transform: translateX(550px);
      }
    }
  </style>
</head>
<body>
  <div id = "element"> Animate </div>
  <br>
  <button onclick = "animateDiv()"> Animate Div </button>
  <script>
    function animateDiv() {
      const element = document.getElementById("element");
      element.style.animation = "moveAnimation 3s ease-in-out infinite";
    }
  </script>
</body>
</html>

動畫化 DOM 元素的最佳方法是使用 `requestAnimationFrame()` 方法,該方法可以平滑地動畫化 DOM 元素。此外,它還可以用於同時執行不同的動畫。

廣告