簡單幾行代碼實現元素背景顏色持續隨機變化,展示 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>
[0, 1) 浮點數,乘以範圍再取整得到整數。rgb(r, g, b),每通道 0-255。clearInterval 停止。requestAnimationFrame 實現更平滑的漸變動畫。ColorAnimator,支持啟停、速度調節、色彩模式切換。隨機背景色是入門 JS 動畫的經典練習,涵蓋定時器、隨機數、樣式操作三大基礎技能。實際項目中建議用 CSS Animation 或 Web Animations API 實現純視覺動畫,性能更優且不阻塞主線程。