這個練習的目標是寫出一個行為近似 jQuery animate() 的函式,並且支援「做完 A 再做 B」的序列效果。示範的動作是:滑鼠移入時先變寬、再變高、最後變不透明;移出時依相反順序還原。
startrun(obj, attr, target, fn)
box.onmouseover = function () {
startrun(box, "width", 200, function () {
startrun(box, "height", 200, function () {
startrun(box, "opacity", "100");
});
});
};
這正是回呼(callback)的威力:一段動畫結束後,呼叫傳進來的 fn,於是三段動畫被串成一條鏈。
if (cur == target) {
clearInterval(obj.timer);
if (fn) { fn(); }
}
<!DOCTYPE html>
<html>
<head>
<meta charset="gb2312" />
<title>animate 動畫</title>
<style>
body { margin:0; padding:0; font:12px/1.5 arial; }
#box {
width:100px; height:100px; position:absolute; background:#06c; left:0;
filter:alpha(opacity=30); opacity:0.3;
}
</style>
<script>
function getstyle(obj, name) {
if (obj.currentStyle) {
return obj.currentStyle[name];
} else {
return getComputedStyle(obj, false)[name];
}
}
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");
});
});
};
};
function startrun(obj, attr, target, fn) {
clearInterval(obj.timer);
obj.timer = setInterval(function () {
var cur = 0;
if (attr == "opacity") {
cur = Math.round(parseFloat(getstyle(obj, attr)) * 100);
} else {
cur = parseInt(getstyle(obj, attr));
}
var speed = (target - cur) / 8;
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
if (cur == target) {
clearInterval(obj.timer);
if (fn) { fn(); }
} else {
if (attr == "opacity") {
obj.style.filter = "alpha(opacity=" + (cur + speed) + ")";
obj.style.opacity = (cur + speed) / 100;
} else {
obj.style[attr] = cur + speed + "px";
}
}
}, 30);
}
</script>
</head>
<body>
<div id="box"></div>
</body>
</html>
這個 startrun 有兩個細節值得學。一是 clearInterval(obj.timer) 放在函式開頭:快速連續觸發時(例如滑鼠在元素上抖動),新的動畫會接管舊的,不會有兩條動畫同時改同一個屬性而互相拉扯。二是 obj.timer 掛在元素身上而非全域變數,讓多個元素能各自獨立動畫——這正是 jQuery 每個元素維護自己動畫佇列的思路。
現代做法用 Web Animations API(element.animate())取代這整套,還能拿到 finished Promise 來串接序列,比回呼巢狀可讀得多。