DIV CSS 佈局教程網

自己動手寫一個JavaScript分頁組件:以十頁為單位的翻頁邏輯
編輯:關於JavaScript     

分頁是列表頁的標配。市面上不乏成熟套件,但自己寫一遍能把幾個常見難題想清楚:總頁數怎麼算、頁碼怎麼在超過十頁時折疊、當前頁如何高亮、切換時怎麼通知外層刷新資料。

這個組件的設計原則是:樣式交給 CSS,結構交給一個空容器,其餘全部由 JS 生成。HTML 那邊只需要一個帶 id 的 DIV。

一、HTML 與 CSS

<ul class="pagination" id="pageDIV">
</ul>

class="pagination" 提供樣式掛載點,id="pageDIV" 供 JS 定位容器。

.pagination {
  margin-top: 10px;
  margin-bottom: 10px;
  display: inline-block;
  padding-left: 0;
  margin: 20px 0;
  border-radius: 4px;
}
.pagination > li {
  display: inline;
}
.pagination > li:first-child > a {
  margin-left: 0;
  border-top-left-radius: 4px;
  border-bottom-left-radius: 4px;
}
.pagination > li > a {
  position: relative;
  float: left;
  padding: 6px 12px;
  margin-left: -1px;
  line-height: 1.42857143;
  color: #337ab7;
  text-decoration: none;
  background-color: #fff;
  border: 1px solid #ddd;
  cursor: pointer;
}
.pagination > li > a.navcur {
  background: #cccccc;
  color: #ffffff;
}

margin-left: -1px 是個小技巧:相鄰兩個 li 的邊框會重疊 1 像素,負邊距把它們壓成一條線,視覺上才不會出現雙倍粗的分隔線。首項加上左右圓角則是為了讓整排頁碼的兩端收得漂亮。

二、組件主體

(以下範例需搭配 jQuery)

/**
 * @pageContentID 渲染分頁的 DIV 元素
 * @curPage      當前開始頁
 * @totalCount   總數量
 * @pageRows     每頁顯示數量
 * @callback     顯示數據的回調函數
 */
function PageList(pageContentID, option) {
  this.pageContentID = document.getElementById(pageContentID);
  this.curPage   = option.curPage;
  this.totalCount = option.totalCount;
  this.pageRows  = option.pageRows;
  this.callback   = option.callback;
  this.pageSize   = Math.ceil(this.totalCount / this.pageRows);
}

PageList.prototype = {
  init: function () {
    this.renderbtn();
  },

  firstpage: function () {
    var _self = this;
    _self._firstpage = document.createElement("li");
    _self._firstpageA = document.createElement("a");
    _self._firstpageA.innerHTML = "首頁";
    _self._firstpage.appendChild(_self._firstpageA);
    this.pageContentID.appendChild(_self._firstpage);
    _self._firstpage.onclick = function () {
      _self.gotopage(1);
    }
  },

  lastpage: function () {
    var _self = this;
    _self._lastpage = document.createElement("li");
    _self._lastpageA = document.createElement("a");
    _self._lastpageA.innerHTML = "尾頁";
    _self._lastpage.appendChild(_self._lastpageA);
    this.pageContentID.appendChild(_self._lastpage);
    _self._lastpage.onclick = function () {
      _self.gotopage(_self.pageSize);
    }
  },

  prewpage: function () {
    var _self = this;
    _self._prew = document.createElement("li");
    _self._prewA = document.createElement("a");
    _self._prewA.innerHTML = "<<";
    _self._prew.appendChild(_self._prewA);
    this.pageContentID.appendChild(_self._prew);
    _self._prew.onclick = function () {
      if (_self.curPage > 1) {
        _self.curPage--;
      }
      _self.callback.call(this, this.curPage);
      _self.init();
    }
  },

  nextpage: function () {
    var _self = this;
    _self._next = document.createElement("li");
    _self._nextA = document.createElement("a");
    _self._nextA.innerHTML = ">>";
    _self._next.appendChild(_self._nextA);
    this.pageContentID.appendChild(_self._next);
    _self._next.onclick = function () {
      if (_self.curPage < _self.pageSize) {
        _self.curPage++;
      }
      _self.callback.call(this, this.curPage);
      _self.init();
    }
  },

  pagenum: function () {
    var _self = this;
    if (this.pageSize <= 10) {
      // 總頁數不超過 10,全部列出
      for (var i = 1, len = this.pageSize; i <= len; i++) {
        _self._num = document.createElement("li");
        _self._numA = document.createElement("a");
        _self._numA.innerHTML = i;
        _self._num.appendChild(_self._numA);
        this.pageContentID.appendChild(_self._num);
        _self._num.onclick = function () {
          var curpage = $(this).text();
          _self.gotopage(curpage);
        }
      }
    } else {
      if (_self.curPage <= 10) {
        // 前 10 頁:顯示 1~10
        for (var i = 1; i <= 10; i++) {
          _self._num = document.createElement("li");
          _self._numA = document.createElement("a");
          _self._numA.innerHTML = i;
          _self._num.appendChild(_self._numA);
          this.pageContentID.appendChild(_self._num);
          _self._num.onclick = function () {
            var curpage = $(this).text();
            _self.gotopage(curpage);
          }
        }
      } else if (_self.curPage > 10 && _self.curPage <= this.pageSize) {
        // 第 11 頁之後:以 10 為一組滑動
          if (this.pageSize < Math.ceil(_self.curPage / 10) * 10) {
            // 尾組頁數不足 10,只列出剩下的
            for (var i = Math.floor(_self.curPage / 10) * 10 + 1; i <= this.pageSize; i++) {
              if (_self.curPage > this.pageSize) return;
              _self._num = document.createElement("li");
              _self._numA = document.createElement("a");
              _self._numA.innerHTML = i;
              _self._num.appendChild(_self._numA);
              this.pageContentID.appendChild(_self._num);
              _self._num.onclick = function () {
                var curpage = $(this).text();
                _self.gotopage(curpage);
               }
            }
        } else {
          if (Math.ceil(_self.curPage / 10) * 10 == _self.curPage) {
            // 剛好落在組邊界:顯示本組 10 頁
            for (var i = _self.curPage - 9; i <= _self.curPage; i++) {
              _self._num = document.createElement("li");
              _self._numA = document.createElement("a");
              _self._numA.innerHTML = i;
              _self._num.appendChild(_self._numA);
              this.pageContentID.appendChild(_self._num);
              _self._num.onclick = function () {
                 var curpage = $(this).text();
                _self.gotopage(curpage);
               }
            }
        } else {
            // 組內:顯示當前所在的 10 頁
            for (var i = Math.floor(_self.curPage / 10) * 10 + 1; i <= Math.ceil(_self.curPage / 10) * 10; i++) {
              _self._num = document.createElement("li");
              _self._numA = document.createElement("a");
              _self._numA.innerHTML = i;
              _self._num.appendChild(_self._numA);
              this.pageContentID.appendChild(_self._num);
              _self._num.onclick = function () {
                 var curpage = $(this).text();
                _self.gotopage(curpage);
               }
            }
        }
      }
    }
    /* 為當前頁加上高亮 class */
    $(".pagination li").each(function () {
      if ($(this)[0].innerText == _self.curPage) {
        $(".pagination li").children("a").removeClass("navcur");
        $(this).children("a").addClass("navcur");
      }
    });
  },

  gotopage: function (curpage) {
    this.curPage = curpage;
    this.callback.call(this, this.curPage);
    this.init();
  },

  renderbtn: function () {
    $(".pagination").html("");
    this.firstpage();
    this.prewpage();
    this.pagenum();
    this.nextpage();
    this.lastpage();
  }
};

三、翻頁規則說明

整個組件以 10 頁為一個單元:

  • 總頁數 ≤ 10:所有頁碼全部列出。
  • 當前頁 ≤ 10:顯示第 1 到 10 頁。
  • 當前頁 > 10:以 Math.floor(curPage / 10) * 10 + 1 到 Math.ceil(curPage / 10) * 10 算出所屬的那一組 10 頁並顯示。
  • 若尾組不足 10 頁,用 this.pageSize < Math.ceil(curPage/10)*10 判斷後只列出剩下的頁碼,避免出現指向不存在頁面的連結。

四、呼叫方式

$(function () {
  var pager = new PageList("pageDIV", {
    curPage: 1,
    totalCount: 26,
    pageRows: 1,
    callback: callbackFuc
  });
  pager.init();
});

function callbackFuc(curpage) {
  // 在這裡依 curpage 向後端請求資料並渲染列表
}

四個參數各有分工:totalCount 與 pageRows 相除後向上取整得到總頁數;callback 是組件與業務解耦的關鍵——分頁只管「告訴你現在在第幾頁」,至於要抓什麼資料、怎麼渲染,全交給外部處理。

五、這份實作可以改進的地方

它能跑,功能也齊全,但仔細看有幾處值得優化:

重複渲染:renderbtn 每次都清空容器再從頭建 DOM,翻頁時整排按鈕被銷毀重建。實務上更常見的做法是只切換 navcur class,其餘節點保持不動。

頁碼生成程式碼重複五次:pagenum 裡那五段幾乎一模一樣的 createElement + onclick 可以抽成一個私有方法 createPageItem(text, handler),程式碼量能砍掉七成。

依賴 innerText 比對:用 $(this)[0].innerText == _self.curPage 判斷當前頁,是字串與數字的比較,且 innerText 在舊 Firefox 上並不支援。把頁碼存進 data-page 屬性再比對會穩妥得多。

缺少邊界處理:的首頁、上一頁在當前頁為 1 時仍可點擊,尾頁、下一頁在最後一頁時同樣如此。加上 disabled 狀態的視覺回饋,使用者才知道自己已經頭尾到底。

每頁一筆的示範參數:範例用 pageRows: 1 是為了方便觀察效果(26 筆資料剛好能看到跨組翻頁),實戰中通常會是 10、20 或 50。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved