想讓一個圖示(例如「OK」標記)沿著直線斜向移動到指定位置嗎?透過 jQuery 的 animate() 方法就能輕鬆實現。本文用一個完整範例示範。
<!DOCTYPE html >
<html>
<head>
<title>圖標線性回歸移動到指定的位置</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body style="font-size: 13px;">
<div>
<div style="margin: 30px 0 30px 0;">
<div style="margin: 50px 0 0 500px;"><b id="b">B</b></div>
<div style="margin: 80px 0 0 300px;"><b id="d">D</b></div>
</div>
<div>
<button name="move">move</button>
<button name="reset">reset</button>
</div>
</div>
<!-- OK 圖標設置成隱藏浮動 -->
<div id="ok" style="display: none; position: absolute; width: 16px; font-color: white; background-color: red;">OK</div>
<script type="text/javascript" src="https://jt.875.cn/js/jquery.js"></script>
<script type="text/javascript">
var pb = {left: $("#b").position().left + $("#b").width(), top: $("#b").position().top};//B 點位置
var pd = {left: $("#d").position().left + $("#d").width(), top: $("#d").position().top};//D 點位置
$("#ok").css({left: pd.left, top: pd.top});//初始將 OK 放在 D 點
$("button[name=move]").click(function() {//點擊 move 按鈕開始從 D 點移動 B 點
$("#ok").fadeIn().animate({
left: pb.left,
top: pb.top
}, 1000,function(){//1 秒內完成動畫,可以設置動畫速度,完了隱藏
$("#ok").fadeOut()
});
});
$("button[name=reset]").click(function() {//點擊 reset 按鈕回到初始狀態
$("#ok").hide().css({left: pd.left, top: pd.top});
});
</script>
</body>
</html>
程式先取得 B、D 兩點的座標,把「OK」圖示的初始位置設在 D 點。點擊 move 按鈕時,用 fadeIn() 讓它出現,再用 animate() 在 1 秒內把 left 與 top 屬性動畫式地改為 B 點座標,營造出沿直線移動的效果,動畫結束後自動淡出隱藏。點擊 reset 則把它歸回原位。透過 animate 同時改變 left 與 top,就能讓元素沿著兩點之間的直線移動。