如果要在學習 jQuery 的過程中挑一個練習題,「圖片輪播」大概是最合適的:它同時涵蓋了 DOM 選取、CSS 操作、animate 動畫、setInterval 排程與插件封裝,程式碼量卻不大。以下從零寫一個淡入淡出式的 Banner 輪播,取名 blockSlide。
淡入淡出的前提是「所有圖片佔據同一塊區域」,因此除了第一張之外,其餘都加上 class="smask" 並以絕對定位疊上去:
<div id="imgADPlayer">
<div id="AdTop">
<div id="myjQueryContent">
<div>
<a href="javascript:void(0)"><img src="_Template/images/photo_01.jpg" alt="" /></a>
</div>
<div class="smask">
<a href="javascript:void(0)"><img src="_Template/images/photo_02.jpg" alt="" /></a>
</div>
<div class="smask">
<a href="javascript:void(0)"><img src="_Template/images/photo_03.jpg" alt="" /></a>
</div>
<div class="smask">
<a href="javascript:void(0)"><img src="_Template/images/photo_04.jpg" alt="" /></a>
</div>
</div>
<div id="flow"></div>
</div>
</div>
div#imgADPlayer
{
margin: auto;
margin-bottom: 4px;
width: 960px;
height: 120px;
background: url(../images/photo_01.jpg) left top no-repeat;
padding: 0px;
border: none;
clear: both;
position: relative; /* 作為內部絕對定位的座標原點 */
}
div#imgADPlayer .smask
{
position: absolute;
left: 0px;
top: 0px;
}
外層必須是 position:relative,否則內層的 absolute 會相對整個頁面定位,圖片就會飛到視窗左上角。這是最常見的 CSS 新手陷阱之一。
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("#AdTop").blockSlide({
speed: "normal", // 淡入淡出的速度
num: 4, // 圖片數量
timer: 3000, // 自動切換間隔(毫秒)
flowSpeed: 300 // 指示器滑塊移動速度
});
});
</script>
/**
* @author huajianhuakai
*/
(function($)
{
$.fn.blockSlide = function(settings)
{
settings = jQuery.extend({
speed: "normal",
num: 4,
timer: 1000,
flowSpeed: 300
}, settings);
return this.each(function()
{
$.fn.blockSlide.scllor($(this), settings);
});
};
$.fn.blockSlide.scllor = function($this, settings)
{
var index = 0;
var imgScllor = $("div:eq(0)>div", $this); // 取出所有圖片層
var timerID;
var MyTime = setInterval(function()
{
ShowjQueryFlash(index);
index++;
if (index == settings.num) { index = 0; }
}, settings.timer);
var ShowjQueryFlash = function(i)
{
$(imgScllor).eq(i)
.animate({ opacity: 1 }, settings.speed)
.css({ "z-index": "100" })
.siblings()
.animate({ opacity: 0 }, settings.speed)
.css({ "z-index": "0" });
};
}
})(jQuery);
核心那一句值得細看:.eq(i) 選出目標圖,動畫到 opacity 1 並把 z-index 拉高;.siblings() 選出它的所有兄弟(也就是其他圖片),動畫到 0 並壓低 z-index。z-index 的切換不可省——若不做,淡入中的新圖會被尚未完全淡出的舊圖遮住,看起來像閃一下才出現。
另外注意 $("div:eq(0)>div", $this) 這個選擇器:第二個參數是 context,限定搜尋範圍在 $this 之內,避免誤選到頁面上其他 div。養成帶 context 的習慣,在複雜頁面上能有效減少誤選與效能浪費。
原始碼作為教學很夠,但要上線還有幾處需要處理。
一、計時器從未清除。timerID 與 MyTime 宣告了卻沒有被使用,計時器永遠在背景跑。滑鼠移入必須暫停,否則使用者還在看第一張,畫面已經自己換走了;移出後再恢復。
二、num 應該自動取得。寫死 4 意味著日後增刪圖片要同步改 JS。改用 $(imgScllor).length 即可,程式碼還更少。
三、指示器與箭頭沒有實作。#flow 留著卻沒有內容,flowSpeed 參數也從未被使用。使用者看到喜歡的圖被換走時,需要一個方式切回去。
四、快速點擊會堆動畫佇列。補上 .stop(true, true) 才能讓新動畫立即接管。
五、無障礙完全缺席。自動播放無法暫停違反 WCAG 2.2.2;螢幕閱讀器也只會讀到一疊 <img>。
整合後的骨架:
(function($){
$.fn.blockSlide = function(opts){
var o = $.extend({ speed: "normal", timer: 3000 }, opts);
return this.each(function(){
var $wrap = $(this),
$imgs = $wrap.find(".smask, div>div").not("#flow"),
total = $imgs.length,
idx = 0, timer = null;
$imgs.css({ position: "absolute", top: 0, left: 0 });
function show(i){
$imgs.eq(i).stop(true, true).animate({opacity:1}, o.speed).css("z-index", 100)
.siblings().stop(true, true).animate({opacity:0}, o.speed).css("z-index", 0);
$imgs.attr("aria-hidden", function(n){ return n === i ? "false" : "true"; });
}
function play(){ stop(); timer = setInterval(function(){ show(idx = (idx+1) % total); }, o.timer); }
function stop(){ if (timer) { clearInterval(timer); timer = null; } }
$wrap.on("mouseenter focusin", stop).on("mouseleave focusout", play);
$wrap.find(".next").on("click", function(){ show(idx = (idx+1) % total); });
$wrap.find(".prev").on("click", function(){ show(idx = (idx-1+total) % total); });
$wrap.find(".pause").on("click", function(){ timer ? stop() : play(); });
show(0);
play();
});
};
})(jQuery);
對和我一樣起步不久的人來說,這個練習的價值不在最終成品,而在於它逼你思考:動畫如何排程、計時器如何回收、狀態如何維護、以及一個「能跑」的東西和一個「能上線」的東西之間還差多少。把上面五點逐一補完,你對 jQuery 的理解就會很不一樣。