DIV CSS 佈局教程網

動手做一個 jQuery 圖片滾動插件:關鍵在「記錄移動步驟的陣列」
編輯:JavaScript綜合知識     

寫過輪播或商品牆的人應該遇過這個尷尬情況:一頁要顯示 7 個項目,但總共只有 10 筆資料。往下一頁時,你不可能再移動 7 格,只能移動剩下的 3 格。這個「最後一屏只走差值」的細節,是很多手作輪播會漏掉的地方。

核心思路

一開始想用一個變數記錄目前移動了幾格,但往前往後都要回推,很快就把自己繞暈了。後來改用陣列來記錄每一次向右移動的步長:向右時 push 進去,向左時 pop 出來,前後就完全對稱了。整個插件的靈魂就在這個 history 陣列。

(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;   // 記錄為空代表沒移動過,直接 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 () {
        // 如果已經是最後一頁,直接 return
        if (this.index == parseInt(this.length / this.config.view, 10)) {
          return;
        }
        this.index++;

        // 這段計算很重要:(下一頁 * view) 是否超過總長度
        // 例如目前在第一頁,(1 + 1) * 7 > 12(總長度),
        // 則 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);

為什麼用陣列就通了

向右移動時把這次的步長 push 進 history,向左時 pop 最後一項並乘上寬度反向動畫,這樣「最後一屏只走 3 格」的情況自然就被正確還原——因為記錄下來的就是 3,不是 7。若用單一變數,你還得另外判斷方向與邊界,反而更容易寫錯。

還可以更好的地方

這份實作用 index 取餘判斷是否到最後一頁,在總數不能被 view 整除時邊界會有點微妙;另外 prev 沒有做「回到第一頁後停用」的處理。如果要繼續打磨,可以考慮把「頁數」與「每頁實際筆數」拆成兩個狀態,並在邊界時切換按鈕的 disabled 樣式。插件化之後,呼叫方式很簡單:

$('.demo').slider({ view: 7, speed: 500 });
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved