DIV CSS 佈局教程網

jQuery animate 實現圖片路徑走位動畫的實例
編輯:JQuery特效代碼     

本文用一個在表格格子間移動的小人圖片,示範如何透過串接多段 animate 動畫,讓元素沿著指定路徑走位。這是理解 animate 串聯與相對位移的好例子。

樣式設定

表格每格 200×200,圖片用相對定位以便透過 left、top 移動:

table{border:1px solid #666;}
table td{border:1px solid #eee;width:200px;height:200px;}
img{width:200px;height:200px;border:none;position:relative;}

核心腳本

透過 i(行)與 c(列計數)兩個變數控制走位邏輯,用相對位移 +=/-= 讓圖片一格一格移動:

<script type="text/javascript">
$(function () {
var i = 0; var c = 0;
$('img').click(function () {
if (c < 3) {
if (i == 2 & c == 0) { $('img').animate({ left: '+=400px', top: '-=200px' }, 1); c++ }
else if (i == 2 & c == 1) { $('img').animate({ left: '-=200px' }, 2000); c++ }
else if (i == 2 & c == 2) { $('img').animate({ left: '-=200px' }, 2000); c = 0; i++; }
else if (i == 3 & c == 0) { $('img').animate({ left: '+=400px', top: '-=200px' }, 1); c++ }
else if (i == 3 & c == 1) { $('img').animate({ left: '-=200px' }, 2000); c++ }
else if (i == 3 & c == 2) { $('img').animate({ left: '-=200px' }, 2000); c++; }
else { $('img').animate({ left: '-=200px' }, 2000); i++; }
}
});
});
</script>

HTML 結構

一個 3×3 的表格,小人圖片放在右下角格子:

<table cellpadding="0" cellspacing="0">
<tr><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td><img src="images/2.gif" alt="奔跑的小人" /></td></tr>
</table>

透過 animate 的串接(方法鏈式呼叫),多段動畫會依序排入佇列自動播放,這正是 jQuery 動畫鏈的強大之處。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved