想用 jQuery 讓元素「走」到某個位置,動畫本身只要一行 animate(),真正容易出錯的地方在 CSS——如果元素的 position 沒有正確設定,left 與 top 的動畫完全不會有效果。
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({left:'250px'});
});
});
</script>
</head>
<body>
<button>Start Animation</button>
<p>By default, all HTML elements have a static position, and cannot be moved.
To manipulate the position, remember to first set the CSS position property
of the element to relative, fixed, or absolute!</p>
<div style="background:#98bf21; height:100px; width:100px;
position:absolute;"></div>
</body>
</html>
所有 HTML 元素的預設 position 值都是 static。在 static 狀態下,left/top/right/bottom 這四個偏移屬性會被瀏覽器忽略,元素只會依文件流排在自己該在的位置。因此要讓偏移生效,必須先改成下列三者之一:
relative:相對自己原本的位置偏移,原本的空間仍保留。absolute:相對最近的已定位祖先元素定位,會脫離文件流。fixed:相對視窗定位,捲動時不動。
$("div").animate({ left: "250px", top: "100px" }, 800, "swing", function(){
console.log("動畫結束");
});
swing 為預設(先快後慢),linear 為等速。動畫佇列:連續快速點擊會讓動畫堆在佇列裡排隊,加上 .stop(true) 可清掉尚未執行的部分。
只能動數字值:animate() 無法處理 auto 或 % 這類需要計算的值,單位也要明確寫出。
相對移動:若要「在目前位置基礎上再往右 50px」,可用 jQuery 的 +=/-= 語法:
$("div").animate({ left: "+=50px" });
最後,若只是簡單的位移且不需要 JS 邏輯介入,用 CSS transition 搭配 transform: translateX() 會更流暢,因為 transform 只觸發合成,不會引起重排(reflow)。