靈感源自經典《JavaScript DOM 編程藝術》(每個 JS 入門者的必讀啟蒙書)。本類僅用 setTimeout + CSS 絕對定位,無任何框架依賴,兼容所有支援 JS 的瀏覽器與環境。
// @Mr.Think -- 簡易動畫類
function moveElem(elemId, final_x, final_y, interval) {
if (!document.getElementById || !document.getElementById(elemId)) return false;
var elem = document.getElementById(elemId);
if (elem.movement) clearTimeout(elem.movement);
// 初始化 left/top
if (!elem.style.left) elem.style.left = "0px";
if (!elem.style.top) elem.style.top = "0px";
var xpos = parseInt(elem.style.left);
var ypos = parseInt(elem.style.top);
if (xpos === final_x && ypos === final_y) return true;
// 計算步長(1/10 距離,向上取整)
if (xpos < final_x) {
var divisor = Math.ceil((final_x - xpos) / 10);
xpos += divisor;
} else if (xpos > final_x) {
var divisor = Math.ceil((xpos - final_x) / 10);
xpos -= divisor;
}
if (ypos < final_y) {
var divisor = Math.ceil((final_y - ypos) / 10);
ypos += divisor;
} else if (ypos > final_y) {
var divisor = Math.ceil((ypos - final_y) / 10);
ypos -= divisor;
}
elem.style.left = xpos + "px";
elem.style.top = ypos + "px";
var repeat = "moveElem('" + elemId + "'," + final_x + "," + final_y + "," + interval + ")";
elem.movement = setTimeout(repeat, interval);
}
<img id="ball" src="ball.png" style="position:absolute; left:0; top:0;" />
<button onclick="moveElem('ball', 300, 200, 20)">移動到 (300,200)</button>
oncomplete 回調、支援相對座標、加入緩動函數(ease-in/out)。若需更豐富動畫(彈性、路徑、鏈式),建議改用 GSAP 或 CSS Transition/Animation;但對於簡單位移,這個 30 行的類已足夠強大。