輪播圖是每個前端都寫過的東西。本文示範一個不依賴任何函式庫的原生實作,功能包含自動播放、底部指示按鈕、滑鼠移入暫停並顯示左右箭頭、移出後從原位置續播,最後還會重構成「一個頁面可以同時跑多個實例」的物件形式。

HTML 結構要求
<div class="carousel-box">
<div class="carousel">
<ul class="clearfix">
<li><img src="img/carousel01.jpg" alt=""></li>
<li><img src="img/carousel02.jpg" alt=""></li>
<li><img src="img/carousel03.jpg" alt=""></li>
<li><img src="img/carousel04.jpg" alt=""></li>
<li><img src="img/carousel05.jpg" alt=""></li>
<li><img src="img/carousel06.jpg" alt=""></li>
</ul>
</div>
</div>
三個硬性要求:必須兩層盒子嵌套、最內層要有 ul、每張圖片包在 li 裡。類名可以自訂,只要同步改 CSS 並在初始化時傳入正確的選擇器即可。圖片數量與尺寸都不限制。
需要調整的 CSS 數值
/* 這三個值要對應調整 */
.carousel img{ width: 600px; height: 400px; }
.carousel, .carousel-box {
width: 600px; /* 單張圖片寬度 */
height: 400px; /* 單張圖片高度 */
}
.carousel ul{
width: 3600px; /* 單張寬度 x 圖片數量 */
}
原理
把所有圖片橫向排成一列,最外層與包裹層都設 overflow:hidden。最外層負責承載按鈕與箭頭的定位,包裹層則靠 scrollLeft 屬性來決定「目前顯示第幾張」。切換圖片,本質上就是在改 scrollLeft。
需要哪些函式
1. 圖片切換函式:接受方向參數,呼叫緩動函式,並更新按鈕高亮
2. 緩動函式
3. 點亮按鈕函式
4. 初始化函式:綁定事件、建立按鈕與箭頭、設定初始位置
5. 建立箭頭函式
6. 建立按鈕函式
7. 開始輪播函式
8. 輪播函式
9. 停止函式
另外幾個公用工具:$() 選取元素、addClass / removeClass 操作類名、$.add(ele,"type",fun) 綁定事件、getCSS(ele,"prop") 讀取樣式、$.delegateTag() 事件代理。
1. 緩動函式 liner
緩動函式的責任是「一點一點改變目標屬性值,直到抵達目標」。它應該夠通用:目標可能是橫向輪播的圖片、縱向輪播的圖片,或是一個要從左跑到右的小方塊。所以只需四個參數:目標元素、要改的屬性、目標值、分成幾次移動。
liner = function(ele, prop, next, num){
var speed = (next - ele[prop]) / num, i = 0;
(function(){
ele[prop] += speed;
i++;
if (i < num) { setTimeout(arguments.callee, 30); }
})();
}
2. 點亮按鈕 light
點亮就是加上 active 類,熄滅就是移除。怎麼知道目前亮著哪一個?最簡單的辦法是記住它——在作用域鏈末端放一個變數 active,每次切換時先把它熄滅。
light = function(index){
removeClass(active, "active");
active = $(this.wrapSelec + " " + "[index=" + index + "]");
addClass(active, "active");
}
3. 圖片切換 go
核心是算出下一個 scrollLeft。往左走就減一個寬度,若已經是 0 則跳到最後一張;往右走就加一個寬度,最後一張回到 0——用取餘的公式最乾淨:
go = function(dire){
var index = active.getAttribute("index") - 0, nextIndex, nextPosition;
if (dire === "next") {
nextIndex = (index + 1) % len;
nextPosition = (ele.scrollLeft + width) % (width * len);
} else {
nextIndex = index === 0 ? len - 1 : index - 1;
nextPosition = ele.scrollLeft === 0 ? width * len : ele.scrollLeft - width;
}
light(nextIndex);
animate.liner(ele, "scrollLeft", nextPosition);
}
其中 len(總張數)、width(單張寬度)、ele(包裹層)會被多個函式共用,一併放到作用域鏈末端。
4. 建立箭頭 createArrow
createArrow = function(){
var prev = document.createElement("div"), next = document.createElement("div");
prev.appendChild(document.createTextNode("<"));
next.appendChild(document.createTextNode(">"));
prev.className = "arrow prev";
next.className = "arrow next";
container.appendChild(prev);
container.appendChild(next);
addClass(container, "hide"); // 預設隱藏,移入才顯示
$.add(next, "click", function(){ go("next"); });
$.add(prev, "click", function(){ go("prev"); });
}
5. 建立按鈕 createBtn
每個按鈕帶一個 index 屬性,供点亮/熄滅時定位:
createBtn = function(){
var div = document.createElement("div"), btns = '';
for (var i = 0; i < len; i++) {
btns += '<a href="#" index="' + i + '"></a>';
}
div.innerHTML = btns;
addClass(div, "carousel-btn");
container.appendChild(div);
}
6. 輪播 circle 與 7. 停止 stop
circle = function(){
count++;
if (loop || count < len) {
if (direction === "forward") { go("next"); }
else { go("prev"); }
}
begin = setTimeout(arguments.callee, t);
}
stop = function(){ clearTimeout(begin); }
8. 初始化 init 與 9. 開始 start
init = function(){
createBtn();
createArrow();
$.delegateTag(wrapSelec + " " + ".carousel-btn", "a", "click", function(e, target){
$.prevent(e);
light(target.getAttribute("index"));
animate.liner(ele, "scrollLeft", target.getAttribute("index") * width);
});
$.add(container, "mouseenter", function(){
stop();
removeClass(container, "hide");
});
$.add(container, "mouseleave", function(){
addClass(container, "hide");
begin = setTimeout(circle, t);
});
if (direction === "forward") {
light(0);
} else {
light(len - 1);
ele.scrollLeft = width * (len - 1);
}
haveStart = true;
}
start = function(dir, th, lo){
stop(); // 重複啟動前先清掉舊計時器
count = 0;
direction = dir;
t = th * 1000;
loop = lo;
if (!haveStart) { init(); }
begin = setTimeout(circle, t);
}
從「單一實例」到「多實例」
把上面所有函式與變數塞進同一個函式裡,對外只暴露 start 與 stop,元件就能用了。但這也意味著一個頁面只能有一個輪播。要支援多實例,就得把狀態放進物件裡——每個物件有自己的屬性,共用同一組方法。
這麼一改,this 立刻變成難題:狀態變成物件屬性後必須用 this 存取,但 this 會指向「呼叫它的那個環境」。在事件處理函式或計時器裡,this 早已不是我們的物件了。解法是閉包——在還拿得到 this 的時候先存起來:
carouselProto.init = function(){
var that = this; // 關鍵:先把 this 存下來
this.createBtn();
this.createArrow();
$.delegateTag(this.wrapSelec + " " + ".carousel-btn", "a", "click", function(e, target){
$.prevent(e);
that.light(target.getAttribute("index"));
animate.liner(that.ele, "scrollLeft", target.getAttribute("index") * that.width);
});
$.add(this.container, "mouseenter", function(){
that.stop();
removeClass(that.container, "hide");
});
$.add(this.container, "mouseleave", function(){
addClass(that.container, "hide");
that.begin = setTimeout(function(){ that.circle(); }, that.t);
});
if (this.direction === "forward") {
this.light(0);
} else {
this.light(this.len - 1);
this.ele.scrollLeft = this.width * (this.len - 1);
}
this.haveStart = true;
};
用原型繼承的方式組織,每個實例擁有自己的狀態屬性,共用原型上的方法:
var carouselProto = {};
carouselProto.light = ...
carouselProto.go = ...
carouselProto.stop = ...
// 生產實例的函式
var carousel = function(eleSelec, wrapSelec){
var that = Object.create(carouselProto);
that.wrapSelec = wrapSelec;
that.ele = $(eleSelec);
that.container = $(wrapSelec);
that.len = that.ele.getElementsByTagName("img").length;
that.width = parseInt(getCSS(that.ele.getElementsByTagName("img")[0], "width"));
return that;
}
// 同一頁面兩個輪播,各自獨立
var carousel1 = carousel(".carousel", ".carousel-box");
carousel1.start("forward", 3, true);
var carousel2 = carousel(".carousel2", ".carousel-box2");
carousel2.start("backward", 2, true);
兩個效能優化
其一,點到的按鈕如果本來就是當前亮著的那張,就不該再跑一次動畫:
$.delegateTag(this.wrapSelec + " " + ".carousel-btn", "a", "click", function(e, target){
$.prevent(e);
var index = target.getAttribute("index");
if (index === that.active.getAttribute("index")) { return }
that.light(index);
animate.liner(that.ele, "scrollLeft", target.getAttribute("index") * that.width);
});
其二,動畫進行中若使用者又點了箭頭,兩段緩動會互相打架導致圖片錯位。加一個旗標記錄動畫狀態就能避免:
liner = function(ele, prop, next){
var speed = (next - ele[prop]) / 10, i = 0;
ele.animating = true;
(function(){
ele[prop] += speed;
i++;
if (i < 10) { setTimeout(arguments.callee, 60); }
else { ele.animating = false; }
})();
}
// 呼叫端加一層守門
if (!this.ele.animating) {
this.light(nextIndex);
animate.liner(this.ele, "scrollLeft", nextPosition);
}
兩個可以更好的地方
範例中的 arguments.callee 在嚴格模式下已被禁用,實作時請改成具名函式表達式(var step = function(){ ... setTimeout(step, 30) })來遞迴。
另外,width 是靠讀取第一張圖片的實際寬度算的,這代表圖片載入完成前初始化會拿到 0。比較穩健的做法是在 CSS 裡固定尺寸,或等 window.onload 之後再初始化,避免首屏出現閃跳。
以上就是原生 JavaScript 輪播元件的完整實作與重構思路,從單檔流程式寫法一路走到可多實例化的物件設計。