萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 實現隨機背景色動畫:setInterval + RGB 動態生成

簡單幾行代碼實現元素背景顏色持續隨機變化,展示 setInterval、隨機數生成、RGB 拼接的基礎應用。

核心代碼

<!doctype html>
<html lang="zh-Hant">
<head>
  <meta charset="UTF-8">
  <title>隨機背景色</title>
  <style>
    #dv { width: 100px; height: 100px; border: 1px solid #ccc; }
  </style>
</head>
<body>
  <div id="dv"></div>
  <script>
    window.onload = function() {
      const box = document.getElementById('dv');
      
      // 隨機整數 [min, max]
      const random = (min, max) => min + Math.floor(Math.random() * (max - min + 1));
      
      setInterval(() => {
        const r = random(0, 255);
        const g = random(0, 255);
        const b = random(0, 255);
        box.style.backgroundColor = `rgb(${r}, ${g}, ${b})`;
      }, 500); // 每 500ms 換一次色
    };
  </script>
</body>
</html>

關鍵點解析

  1. Math.random() 返回 [0, 1) 浮點數,乘以範圍再取整得到整數。
  2. RGB 格式:rgb(r, g, b),每通道 0-255。
  3. setInterval:周期性執行,返回定時器 ID,可用 clearInterval 停止。
  4. 模板字符串:ES6 語法構建 CSS 值,可讀性強。

優化建議

  • 使用 requestAnimationFrame 實現更平滑的漸變動畫。
  • 添加 HSL 色彩空間控制,生成協調的配色序列。
  • 封裝為可復用類 ColorAnimator,支持啟停、速度調節、色彩模式切換。

總結

隨機背景色是入門 JS 動畫的經典練習,涵蓋定時器、隨機數、樣式操作三大基礎技能。實際項目中建議用 CSS Animation 或 Web Animations API 實現純視覺動畫,性能更優且不阻塞主線程。

copyright © 萬盛學電腦網 all rights reserved