不想引入 jQuery,又想實現 animate() 那樣流暢的屬性過渡,其實並不難。本文的示例做到:鼠標移入時依次改變寬度、高度、透明度;移出時再按相反順序變回去。
startrun(obj, attr, target, fn)
box.onmouseover = function () {
startrun(box, "width", 200, function () {
startrun(box, "height", 200, function () {
startrun(box, "opacity", "100");
});
});
};
函數在 JavaScript 裡是一等值,可以作為參數傳入。利用回調嵌套,就能實現「做完 A 再做 B」的串行動畫。
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>
這套寫法的價值在於它把「定時器 + 步長 + 完成回調」抽象成了一個通用函數,任何數值型 CSS 屬性都能複用。如果追求更細的控制(多屬性並行、easing 曲線、隊列),現階段更推薦直接上 requestAnimationFrame 或 Web Animations API。