本文分享一個用原生 JS 實現的圖片輪播組件,支援自動播放、按鈕切換、手勢箭頭以及多實例共存。
自動循環播放圖片,下方有按鈕可切換到對應圖片;
切換時帶緩動動畫;
滑鼠移入圖片區域時暫停輪播,並出現左右箭頭,點擊可切換;
滑鼠移開後從當前位置繼續輪播;
對外提供接口,可設置輪播方向、是否循環、間隔時間。
<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 中的對應選擇器,配置組件時傳入正確的 DOM 元素即可;
圖片寬度與數量不受限制,改 CSS 裡的數值就行。
/* 需要更改的值 */
.carousel img {
width: 600px;
height: 400px;
}
.carousel, .carousel-box {
width: 600px; /* 單張圖片寬度 */
height: 400px; /* 單張圖片高度 */
}
.carousel ul {
width: 3600px; /* 單張圖片寬度 x 圖片數量 */
}
把所有圖片橫向排列,最外層容器與包裹容器都設 overflow: hidden。最外層容器負責按鈕與箭頭的定位,包裹容器則用 scrollLeft 屬性控制當前顯示第幾張圖。
1. 圖片切換函數:接收一個表示滾動方向的參數,調用緩動函數完成切換,並點亮對應按鈕;
2. 緩動函數;
3. 點亮按鈕函數;
4. 初始化函數:綁定事件、創建按鈕與箭頭、設置初始位置;
5. 創建箭頭函數;
6. 創建按鈕函數;
7. 開始輪播函數;
8. 輪播函數;
9. 停止函數。
另外還需要幾個公用方法:
$() 選擇 DOM 元素;addClass / removeClass 增刪類名;$.add(ele, type, fun) 綁定事件;getCSS(ele, prop) 讀取樣式值;$.delegateTag(selector, tagName, type, fun) 事件代理。
假設 6 張圖片、每張寬 600px,按功能獨立性逐一完成。
緩動函數的作用是一點一點改變目標元素的屬性值直到抵達目標。它可能服務於水平輪播的圖片、垂直輪播的圖片,也可能只是一個從左跑到右的小方塊,因此接收四個參數:目標元素、要改變的屬性、目標值、移動次數。
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);
}
})();
},
點亮本質上就是加一個 active 類,熄滅則是移除它。要知道當前亮著的是哪個按鈕,可以在作用域鏈末端放一個變數 active 記住它;而每個按鈕都帶一個 index 屬性,傳入要點亮的 index 即可。
light = function (index) {
removeClass(active, "active");
active = $(this.wrapSelec + " " + "[index=" + index + "]");
addClass(active, "active");
}
核心是把下一個 scrollLeft 算準。向左移動時 scrollLeft 減 600,若已是 0 則跳到 3000;向右移動時加 600,0→600→1200→…→3000→0,這裡可以直接用取模公式 next = (cur + distance) % (distance * num)。按鈕 index 同理:向左 index === 0 ? len - 1 : index - 1,向右 (index + 1) % len。
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(包裹容器)會被多個函數共用,一併掛到作用域鏈末端:
len = ele.getElementsByTagName("img").length;
width = parseInt(getCSS(ele.getElementsByTagName("img")[0], "width"));
//ele = $(eleSelec),eleSelec 是包裹容器的 selector,例如 .carousel
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"); });
}
//container = $(wrapSelec),wrapSelec 是最外層容器的 selector,例如 .carousel-box
給每個按鈕加 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);
}
根據方向決定呼叫 go("next") 還是 go("prev");若要求循環則再次調用自身,否則輪播一輪後停止。這裡需要 direction(方向)、loop(是否循環)、count(計數)、begin(定時器 ID,用於清除)四個變數。
circle = function () {
count++;
if (loop || count < len) {
if (direction === "forward") {
go("next");
} else {
go("prev");
}
}
begin = setTimeout(arguments.callee, t);
}
stop = function () {
clearTimeout(begin);
}
首次使用時創建按鈕與箭頭,給按鈕綁定 click(取出點擊項的 index,點亮它並切換到對應圖片),再依順/逆時針展示初始圖與按鈕。這裡還需要一個 haveStart 變數標記是否已初始化。
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);
}
把上述變數與函數一股腦塞進同一個函數,確實能跑,但代價是一個頁面只能有一個輪播實例。想讓同頁出現兩個輪播,就得改用對象:每個對象持有自己的狀態變數,共用同一組方法。
此時變數不能直接訪問,要透過 this。問題隨之而來——this 指向的是呼叫它的環境,因此在事件處理器或定時器回調裡,this 已經不是我們想要的那個對象了。解法是創建閉包:在能拿到 this 的地方把它存進一個變數(慣例是 that),後續在回調中訪問該變數。
carouselProto.init = function () {
var that = 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);
1. 避免重複點擊的無效計算。若點擊的正是當前已點亮的按鈕,直接 return,不必再跑 light 與動畫:
$.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);
});
2. 防止動畫未結束就被打斷。緩動動畫執行期間若使用者又點了按鈕或箭頭,就會疊加新的動畫,導致圖片錯位、性能下降。用一個標記位記錄動畫狀態即可:
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);
}
參考資源:慕課網「焦點圖輪播特效」、《JavaScript: The Good Parts》。