目標效果
- 滑鼠進入:寬度 100→200 → 高度 100→200 → 透明度 0.3→1
- 滑鼠離開:反向序列 200→100
- 每階段完成後自動觸發下一階段(回調鏈)
核心模式:回調函數作為參數傳遞
startRun(el, 'width', 200, function() { // 階段1
startRun(el, 'height', 200, function() { // 階段2
startRun(el, 'opacity', 100); // 階段3
});
});
通用動畫引擎實現
function getStyle(el, prop) {
return el.currentStyle ? el.currentStyle[prop] : getComputedStyle(el, false)[prop];
}
function startRun(el, attr, target, cb) {
clearInterval(el.timer);
el.timer = setInterval(function() {
var cur = attr === 'opacity'
? Math.round(parseFloat(getStyle(el, attr)) * 100)
: parseInt(getStyle(el, attr));
var speed = (target - cur) / 8;
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
if (cur === target) {
clearInterval(el.timer);
cb && cb(); // 執行下一階段回調
} else {
if (attr === 'opacity') {
el.style.filter = 'alpha(opacity=' + (cur + speed) + ')';
el.style.opacity = (cur + speed) / 100;
} else {
el.style[attr] = cur + speed + 'px';
}
}
}, 30);
}
完整交互代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="gb2312">
<title>串聯動畫</title>
<style>
#box { width: 100px; height: 100px; position: absolute; background: #06c; left: 0; filter: alpha(opacity=30); opacity: 0.3; }
</style>
</head>
<body>
<div id="box"></div>
<script>
window.onload = function() {
var box = document.getElementById('box');
box.onmouseover = function() {
startRun(box, 'width', 200, function() {
startRun(box, 'height', 200, function() {
startRun(box, 'opacity', 100);
});
});
};
box.onmouseout = function() {
startRun(box, 'height', 100, function() {
startRun(box, 'width', 100, function() {
startRun(box, 'opacity', 30);
});
});
};
};
</script>
</body>
</html>
進階:Promise 封裝實現 async/await 風格(ES6+)
function animate(el, attr, target) {
return new Promise(resolve => {
startRun(el, attr, target, resolve);
});
}
// 使用
box.onmouseover = async function() {
await animate(box, 'width', 200);
await animate(box, 'height', 200);
await animate(box, 'opacity', 100);
};
生產級動畫庫設計要點
- requestAnimationFrame 替代
setInterval,與瀏覽器重繪同步,更流暢省電
- 緩動函數庫:內置 linear/ease-in/ease-out/ease-in-out/彈性/彈跳等
- 層級合成:
transform: translate/scale/rotate + opacity 觸發 GPU,避免重排
- 並行/序列控制:
Promise.all(並行)vs await 鏈(序列)
- 中斷/暫停/恢復:暴露
pause()/resume()/cancel() API