用過很多別人的輪播外掛,總算自己寫了一個,留個紀念。這個版本的功能很基本:圖片定時切換,滑鼠移入時暫停動畫,移開後從上次位置繼續。
/*
* banner 0.1
* 使用 banner 實現圖片定時切換
* 滑鼠經過停止動畫,滑鼠離開繼續動畫
*/
;(function ($) {
$.fn.banner = function (options) {
// 各種屬性和參數
var defaults = {
picWidth: "1000",
picHeight: "300",
speed: "1500"
};
var totalW = 0; // 保存總的動畫寬度
var timer = null; // 保存定時器
var current = 0; // 保存當前動畫到第 N 張圖,下次從這裡開始
var totalNum = 0; // 保存總的圖數
var Dsqtime = 0; // 定義定時器時間(外傳參數)
var Dhtime = 0; // 定義動畫時間
var count = 0;
// 合併多個物件為一個:有新參數用新的,否則用預設
var options = $.extend(defaults, options);
this.each(function () {
var __this = $(this);
Dsqtime = options.speed;
Dhtime = Dsqtime / 3;
init(__this); // 初始化
show(__this, options.picWidth, current); // 調用動畫
// 滑鼠經過時清除定時器
__this.find('ul li').bind('mouseover', function () {
window.clearInterval(timer);
});
// 滑鼠離開時接著上一次的動畫輪播
__this.find('ul li').bind('mouseout', function () {
show(__this, options.picWidth, current);
});
});
// 初始化:設定父容器寬度
function init(obj) {
obj.find('ul li').each(function () {
totalW += $(this).width();
totalNum++;
});
obj.find('ul').width(totalW);
}
// 開始動畫顯示
function show(obj, width, current) {
timer = setInterval(function () {
obj.find('ul').animate({ 'margin-left': '-' + count * width + 'px' }, Dhtime);
current = count;
count++;
if (count == totalNum) { count = 0; }
}, Dsqtime);
}
};
})(jQuery);
結構非常單純:一個外層容器,裡頭一個 ul,每張圖各自一個 li。所有 li 浮動排成一列,靠改變 ul 的 margin-left 來推移畫面。
<!doctype html>
<html>
<head>
<meta charset="utf8"/>
<script type="text/javascript" src="./js/jquery.min.js"></script>
<script type="text/javascript" src="./js/jquery.banner.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('.wrap').banner({
picWidth: "1000",
picHeight: "300",
speed: "6000"
});
});
</script>
<style type="text/css">
* { margin:0; padding:0; }
.wrap { width:1000px; height:300px; overflow:hidden; margin:0 auto; }
.wrap ul li { float:left; list-style:none; }
.wrap ul li img { width:1000px; height:300px; }
.clear { clear: both; }
</style>
</head>
<body>
<div>
<div class="wrap">
<ul>
<li><a href="#"><img src="./images/1.jpg"/></a></li>
<li><a href="#"><img src="./images/2.jpg"/></a></li>
<li><a href="#"><img src="./images/3.jpg"/></a></li>
<li><a href="#"><img src="./images/4.jpg"/></a></li>
<li><a href="#"><img src="./images/5.jpg"/></a></li>
</ul>
<div class="clear"></div>
</div>
</div>
</body>
</html>
效果圖:

這個版本能跑,但仍有幾處值得改進,正好當成練習題:
循環不順:播到最後一張後 count 歸零,ul 會瞬間從最右邊「跳」回最左邊。標準解法是在末尾再複製一份第一張圖,播完後以零耗時瞬間歸位。
mouseover/mouseout 會被 li 觸發多次:滑鼠在多個 li 之間移動時事件會反覆觸發。改用 mouseenter/mouseleave,或掛在容器上並用 .hover(),行為才符合預期。
$.extend 的方向:$.extend(defaults, options) 會直接改動 defaults 這個物件本身。雖然本例中 defaults 每次都重新建立所以無妨,但養成寫成 $.extend({}, defaults, options) 的習慣比較安全。
缺少可配置項:目前動畫時間被寫死成 speed 的三分之一,實務上應該獨立成一個參數。
更多 jQuery 相關內容有興趣者可查看本站專題:《jQuery 常用外掛及用法總結》、《jQuery 擴充技巧總結》、《jQuery 切換特效與技巧總結》、《jQuery 遍歷演算法與技巧總結》、《jQuery 常見經典特效匯總》、《jQuery 動畫與特效用法總結》及《jQuery 選擇器用法總結》。