本文用一個會沿著表格格子移動的「落淚小孩」圖片,示範 animate 動畫的串接,並重點說明 stop() 與 delay() 兩個實用方法。
表格 3×3,圖片用相對定位:
img { width:150px; height:200px; position:relative; }
td{ width:150px; height:200px; }
table{ border:solid 1px black; }
點擊圖片後,用鏈式呼叫串接多段 animate,讓它繞行一圈;再用兩個按鈕分別示範 stop 與 delay:
<script type="text/javascript">
$(function () {
$('img').click(function () {
$(this).animate({ left: '+=150px' }, 2000)
.animate({ left: '+=150px' }, 2000)
.animate({ top: '+=200px' }, 2000)
.animate({ left: '-=150px' }, 2000)
.animate({ left: '-=150px' }, 2000)
.animate({ top: '+=200px' }, 2000)
.animate({ left: '+=150px' }, 2000)
.animate({ left: '+=150px' }, 2000);
});
// 停止動畫:當元素有動畫佇列時,stop 的是當前動畫,接著執行下一個
$('#btnStop').click(function () {
$('img').stop();
});
// 延遲執行
$('#btnYanChi').click(function () {
$('img').delay(2000).hide(2000);
});
});
</script>
包含一個 3×3 表格、圖片與兩個控制按鈕:
<table> <tr><td><img src="images/淚奔1.gif" /></td><td></td><td></td></tr> <tr><td></td><td></td><td></td></tr> <tr><td></td><td></td><td></td></tr> </table> <input id="btnStop" type="button" value="stop" /> <input id="btnYanChi" type="button" value="延遲執行" />
重點整理:stop() 用來中止當前動畫,避免動畫堆疊;delay() 則是在動畫佇列中插入一段等待時間,讓後續動畫延遲播放,兩者在製作複雜動畫序列時非常實用。