原生 JS 動畫是理解前端動畫本質的基石。雖然現代開發多使用 CSS Animation、Web Animations API 或 GSAP 等庫,但掌握定時器、緩動函數、幀率控制等核心概念,有助於深度排查動畫效能問題、實現高度自定義效果。
function linearMove(element, targetLeft, duration) {
const start = performance.now();
const startLeft = element.offsetLeft;
const distance = targetLeft - startLeft;
function step(now) {
const elapsed = now - start;
const progress = Math.min(elapsed / duration, 1);
element.style.left = startLeft + distance * progress + 'px';
if (progress < 1) requestAnimationFrame(step);
}
requestAnimationFrame(step);
}
關鍵:使用 requestAnimationFrame 替代 setInterval,配合時間戳計算進度,不受幀率波動影響。
function fade(element, targetOpacity, duration) {
const start = performance.now();
const startOpacity = parseFloat(getComputedStyle(element).opacity) || 1;
const distance = targetOpacity - startOpacity;
function step(now) {
const progress = Math.min((now - start) / duration, 1);
element.style.opacity = startOpacity + distance * progress;
if (progress < 1) requestAnimationFrame(step);
}
requestAnimationFrame(step);
}
IE8- 需同時設定 filter: alpha(opacity=...),現代項目可忽略。
線性動畫感覺生硬,引入緩動函數模擬物理真實感:
const Easing = {
linear: t => t,
easeInQuad: t => t * t,
easeOutQuad: t => t * (2 - t),
easeInOutQuad: t => t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t,
// 更多:https://easings.net/
};
function animate(element, properties, duration, easingName = 'easeOutQuad') {
const easing = Easing[easingName] || Easing.linear;
const start = performance.now();
const startValues = {};
for (const prop in properties) {
startValues[prop] = parseFloat(getComputedStyle(element)[prop]) || 0;
}
function step(now) {
const progress = Math.min((now - start) / duration, 1);
const eased = easing(progress);
for (const prop in properties) {
const distance = properties[prop] - startValues[prop];
element.style[prop] = startValues[prop] + distance * eased + (prop === 'opacity' ? '' : 'px');
}
if (progress < 1) requestAnimationFrame(step);
}
requestAnimationFrame(step);
}
每個元素維護獨立的定時器 ID、目標值、當前值,避免共用定時器導致相互干擾。
function startMove(element, targetProps, duration, easing) {
// 取消該元素正在進行的動畫
if (element._animTimer) cancelAnimationFrame(element._animTimer);
const start = performance.now();
const startProps = {};
for (const p in targetProps) startProps[p] = parseFloat(getComputedStyle(element)[p]) || 0;
function step(now) {
const progress = Math.min((now - start) / duration, 1);
const eased = Easing[easing](progress);
for (const p in targetProps) {
element.style[p] = startProps[p] + (targetProps[p] - startProps[p]) * eased + (p === 'opacity' ? '' : 'px');
}
if (progress < 1) element._animTimer = requestAnimationFrame(step);
else element._animTimer = null;
}
element._animTimer = requestAnimationFrame(step);
}
function getStyle(element, prop) {
return window.getComputedStyle ? getComputedStyle(element)[prop] : element.currentStyle[prop];
}
// 注意:getComputedStyle 回傳的寬高包含 padding、border(box-sizing: border-box 時),需注意 box-sizing 差異。
將屬性名、目標值以物件傳入,支援 opacity、width、height、left、top、marginLeft 等任意數值屬性。對 opacity 特殊處理(不加 px、用 parseFloat)。
function animateAsync(element, props, duration, easing) {
return new Promise(resolve => {
animate(element, props, duration, easing);
// 簡易輪詢檢查完成(實際應在 animate 內部 resolve)
const check = setInterval(() => {
if (!element._animTimer) { clearInterval(check); resolve(); }
}, 16);
});
}
// 使用
await animateAsync(box, { left: 200 }, 500, 'easeOutQuad');
await animateAsync(box, { top: 200 }, 500, 'easeInQuad');
單次 animate 呼叫即可傳入多屬性物件,內部同一幀更新所有屬性,保證同步:
animate(box, { left: 300, top: 200, opacity: 0.5, width: 100 }, 800, 'easeInOutQuad');
transform / opacity(合成層動畫,不觸發佈局/重繪)。will-change: transform, opacity 提前提升合成層。offsetWidth 等),造成強制同步佈局。requestAnimationFrame 批次處理或 Web Workers + OffscreenCanvas。掌握這 8 大核心知識點,即可構建一個輕量、高效、可擴展的原生動畫引擎。實際專案中,簡單動畫首選 CSS,複雜序列、物理模擬、拖拽聯動等場景再考慮 JS 或 GSAP。