萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 圖片輪播插件實作:歷史記錄陣列實現精準前後導航、支援不足一頁補齊邏輯

插件特色

  • 水平無縫輪播,可設定可視數量 (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);

HTML 結構

<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 播報頁碼。

現代替代庫

  • Swiper (功能最全、支援虛擬滑塊、SSR、React/Vue/Svelte 組件)
  • Glide.js (輕量 23kb、無依賴、ESM)
  • Embla Carousel (核心極簡、插件化、TypeScript 原生)
  • Flickity (拖曳物理感、免費開源)

總結

歷史記錄陣列是解決「不足一頁步數不一致」的巧妙設計。插件結構清晰,易於擴充。生產環境建議直接採用成熟庫,專注業務邏輯而非重複造輪子。

copyright © 萬盛學電腦網 all rights reserved