早期 JS 動畫演示:絕對定位元素配合 setTimeout 循環修改 top/left 實現移動、碰撞反彈、背景閃爍、粒子上升。
let step = 1, x = 1, y = -1;
function floatImg(){
const img = document.getElementById('myImg');
let top = parseInt(img.style.top) || 0;
let left = parseInt(img.style.left) || 0;
if(top <= 0) y = 1;
if(top >= document.body.clientHeight - img.offsetHeight) y = -1;
if(left <= 0) x = 1;
if(left >= document.body.clientWidth - img.offsetWidth) x = -1;
img.style.top = (top + step * y) + 'px';
img.style.left = (left + step * x) + 'px';
setTimeout(floatImg, 20);
}
window.onload = floatImg;
const colors = ['yellow','coral','orange','red','greenyellow','lime','turquoise','blueviolet','violet'];
let pos = 0;
function chgCol(){
document.bgColor = colors[pos++ % colors.length];
setTimeout(chgCol, 500);
}
// 圖片彈跳邏輯同案例一,配合 scrollLeft/scrollTop 適配滾動頁面
// 核心邏輯:60 個氣泡,隨機 X,Y 從底部向上,速度隨機,超出頂部重置
// 代碼較長,核心思想:
// 1. 創建 60 個 <img src="bubble.png" style="position:absolute">
// 2. 定時器更新每個氣泡 y -= speed,x 微調模擬擺動
// 3. y < -size 時重置到底部隨機 x
element.animate(keyframes, options) 原生 JS 控制。requestAnimationFrame 繪製,性能碾壓 DOM 操作。本文代碼展示了 DOM 逐幀動畫的原始形態,理解其「定時器+座標計算」本質,有助於深入掌握現代動畫引擎的底層邏輯。