每幀速度 = (目標位置 - 當前位置) / 系數。隨著距離縮小,速度遞減,形成「快進慢出」效果。
取整關鍵:正向 Math.ceil、反向 Math.floor,保證最後一幀能精確到達目標,避免無限逼近不等於。
<!DOCTYPE html>
<html>
<head>
<meta charset="gb2312">
<title>緩動運動</title>
<style>
body { margin: 0; padding: 0; font: 12px/1.5 Arial; }
#box { width: 100px; height: 100px; position: absolute; background: #06c; left: 0; }
</style>
</head>
<body>
<input id="btn" type="button" value="向右運動">
<div id="box"></div>
<br>
<textarea id="log" cols="50" rows="10" style="margin-top:130px"></textarea>
<script>
window.onload = function() {
var box = document.getElementById('box');
var btn = document.getElementById('btn');
var log = document.getElementById('log');
var timer = null;
btn.onclick = function() { startRun(300); };
function startRun(target) {
clearInterval(timer);
timer = setInterval(function() {
var speed = (target - box.offsetLeft) / 8;
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
if (box.offsetLeft === target) {
clearInterval(timer);
} else {
box.style.left = box.offsetLeft + speed + 'px';
}
log.value += box.offsetLeft + ',' + speed + '\n';
}, 30);
}
};
</script>
</body>
</html>
| 參數 | 影響 | 建議範圍 |
|---|---|---|
| 除數 (代碼中 8) | 越大 → 緩動越緩慢、時間越長 | 5-15 |
| 定時器間隔 (30ms) | 越小 → 幀率越高、CPU 佔用越大 | 16ms (≈60fps) 或 30ms |
| 目標值 | 決定運動距離與總時長 | 業務決定 |
function easeOutQuad(t) { return t * (2 - t); } // t: 0-1
function animate(el, prop, target, duration, cb) {
var start = performance.now();
var from = parseFloat(getComputedStyle(el)[prop]);
var isOpacity = prop === 'opacity';
function frame(now) {
var p = Math.min((now - start) / duration, 1);
var eased = easeOutQuad(p);
var val = from + (target - from) * eased;
el.style[prop] = isOpacity ? val : val + 'px';
if (p < 1) requestAnimationFrame(frame);
else cb && cb();
}
requestAnimationFrame(frame);
}
// 使用
animate(box, 'left', 300, 800, function() { console.log('done'); });
anime.js、gsap、motion-one