圖片輪播寫到最後一頁時,最常見的 bug 是「後面補不滿,畫面出現空白」。本文記錄一個解法的核心思路:用一個陣列記錄每次移動的步數,前進時 push、後退時 pop。
當剩餘項目數量少於一屏可顯示的數量時,不要硬移滿一屏,而是只移動「顯示個數 − 剩餘個數」的差值。
舉例:每屏顯示 7 個,總共 10 個。第一屏顯示第 1–7 個;按下一頁時,使用者應該看到第 4–10 個,也就是只移動 3 個而不是 7 個。這樣畫面永遠填滿,不會露出空白。
(function( $ ){
var slider = function( elem, args ){
this.config = $.extend({
effect: 'x', // 效果方向,水平為 x
speed: 600, // 動畫速度
trigger: 'mouseenter', // 觸發事件
callback: null, // 回調函數
view: 7 // 每屏顯示數量
}, args || {});
this.history = []; // 記錄移動的歷史步驟
this.index = 0; // 當前頁索引
this.el = elem;
this.length = this.el.find('li').length; // 總項目數
this.width = this.el.find('li').eq(0).outerWidth(); // 單項寬度
this.init();
};
slider.prototype = {
constructor: slider,
init: function(){
this.bindEvents();
},
bindEvents: function(){
this.prev();
this.next();
},
prev: function(){
this.el.find('[data-type="left"]').click( $.proxy(function(){
if ( !this.history.length ) return; // 沒移動過,直接返回
this.index--;
var step = this.history.pop(); // 取回上次的步驟
var move = step * this.width; // 換算成像素
this.el.find("ul").animate({ "left": "+=" + move + "px" },
this.config.speed);
}, this));
},
next: function(){
this.el.find('[data-type="right"]').click( $.proxy(function(){
// 判斷是否已到最後一頁
if ( this.index == parseInt(this.length / this.config.view, 10) ) {
return;
}
this.index++;
// 關鍵計算:下一頁的顯示範圍是否超出總長度
// 例如目前在第一頁,(1+1)*7 = 14 > 10(總長度)
// 則 step 取餘數,也就是剩下要移動的個數
if ( this.config.view * (this.index + 1) > this.length ) {
this.step = this.length % this.config.view;
} else {
this.step = this.config.view;
}
this.history.push(this.step);
var move = -1 * this.step * this.width;
this.el.find("ul").animate({ "left": "+=" + move + "px" },
this.config.speed);
}, this));
}
};
$.fn.slider = function( args ){
return this.each(function(){
var el = this;
var plugins = new slider( $( el ), args );
$(el).data("slider", plugins);
});
};
})(jQuery);
最初的想法是用一個變數記住「目前在第幾屏」,再回推每次該移多少。但這個思路在「最後一屏只移 3 格」的規則下會卡住:從第 4 屏退回第 3 屏時,該移 3 格還是 7 格?用單一變數無法區分不同頁的步長。
改用陣列之後問題自然消解。前進時把當次實際步長 push 進去,後退時 pop 出來用,每一步都記得自己走了多遠,不需要任何回推計算。這是把「狀態」明確記錄下來、而不是試圖從結果反推的典型例子。
索引判斷有 bug。this.index == parseInt(this.length / this.config.view, 10) 在總數能被整除時會多允許一次點擊。10 個項目、每屏 7 個,頁數應為 2(索引 0、1),但 parseInt(10/7) = 1,所以索引 1 時就會被擋住——總共只能前進一次,剛好對;可是若總數是 14、每屏 7,parseInt(14/7) = 2,索引會走到 2 才擋,也就是允許前進三次,多了一次空白頁。正確做法是用 Math.ceil(length / view) - 1 計算最大索引。
取模的邊界。當 length % view === 0 時,this.step 會變成 0,按鈕雖然不會報錯但也什麼都不做。需要一併處理。
$.proxy 已不建議使用。它是綁定 this 的舊寫法,現代做法是用 ES6 的箭頭函式,或用 bind()。
可存取性完全缺席。輪播應該提供上一頁/下一頁的真實 <button>(而非靠 data-type 的 div),加上 aria-label,並讓自動播放可以暫停。圖片也要有合適的 alt 文字。
用 transform 而非 left。動畫 left 會觸發重排(reflow),效能不如 transform: translateX(),後者只走合成(composite)階段,在行動裝置上順暢度差異明顯。