view)、動畫速度 (speed)、觸發事件 (trigger)。this.history) 記錄每次移動的步數,點擊「上一頁」精準回退對應距離,解決最後一頁不足一頁時步數不同步問題。callback)。(function($) {
var Slider = function(el, options) {
this.$el = $(el);
this.cfg = $.extend({
effect: 'x', // 僅水平
speed: 600,
trigger: 'click', // click / hover
view: 7, // 可視項目數
callback: null
}, options);
this.$list = this.$el.find('ul');
this.$items = this.$list.children('li');
this.len = this.$items.length;
this.itemW = this.$items.eq(0).outerWidth(true); // 含 margin
this.history = []; // 關鍵:記錄每次前進步數
this.index = 0; // 當前頁索引
this.maxIndex = Math.ceil(this.len / this.cfg.view) - 1;
this.bind();
};
Slider.prototype.bind = function() {
var self = this;
this.$el.find('[data-type="left"]').on(this.cfg.trigger, function() { self.prev(); });
this.$el.find('[data-type="right"]').on(this.cfg.trigger, function() { self.next(); });
};
Slider.prototype.prev = function() {
if (!this.history.length) return; // 尚未前進過
this.index--;
var step = this.history.pop(); // 取出上次前進步數
this.animate(-step * this.itemW);
};
Slider.prototype.next = function() {
if (this.index >= this.maxIndex) return; // 已在最後一頁
this.index++;
// 計算本次應移動步數
var remaining = this.len - this.index * this.cfg.view;
var step = (remaining >= this.cfg.view) ? this.cfg.view : remaining; // 最後一頁補齊邏輯
this.history.push(step);
this.animate(step * this.itemW);
};
Slider.prototype.animate = function(dx) {
var self = this;
this.$list.stop(true, true).animate({ left: '+=' + dx + 'px' }, this.cfg.speed, function() {
if (self.cfg.callback) self.cfg.callback(self.index);
});
};
$.fn.slider = function(options) {
return this.each(function() {
if (!$(this).data('slider')) {
$(this).data('slider', new Slider(this, options));
}
});
};
})(jQuery);
<div class="slider-container">
<button data-type="left">‹</button>
<div class="viewport">
<ul>
<li><img src="1.jpg"></li>
<li><img src="2.jpg"></li>
...
</ul>
</div>
<button data-type="right">›</button>
</div>
$('.slider-container').slider({
view: 5,
speed: 500,
trigger: 'click',
callback: function(idx) { console.log('當前頁:', idx); }
});
總項目 12,view=7 第 1 頁 (index=0) → 顯示 0-6 點擊 Next → step = min(7, 12-7)=5 → history=[5], index=1 → 顯示 5-11 (共 7 項,前 2 項為第 1 頁後段) 點擊 Prev → pop 5 → step=5 → index=0 → 精準回到第 1 頁
setInterval(() => next(), 3000),滑鼠進入暫停。touchstart/move/end 計算位移觸發 prev/next。resize 重算 itemW、view、maxIndex 並重置位置。aria-label、鍵盤左右鍵控制、aria-live 播報頁碼。歷史記錄陣列是解決「不足一頁步數不一致」的巧妙設計。插件結構清晰,易於擴充。生產環境建議直接採用成熟庫,專注業務邏輯而非重複造輪子。