js 分页控件
不知道 这算不算是一个控件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
; (function (win) { var settings = { pageIndex: 10, pageSize: 8, total: 100,//总记录数,而不是总页数 showNext: true, preOption: false, changPage: false, nextText: 'Next->', prevText: '<-Prev', /*下面全部都是一些dom的定义begin*/ pageClass: 'tt', pageDom: 'a', /*上面全部都是一些dom的定义end */ }; function CreatePageDom(pageIndex) { var dom = document.createElement(settings.pageDom); if (settings.pageDom == 'a') { dom.setAttribute('href', 'javascript:void(0);'); } dom.innerText = pageIndex; if (pageIndex == settings.pageIndex) { try { dom.classList.add(settings.pageClass); } catch (e) { dom.className = settings.pageClass; } } dom.addEventListener('click', (function (p) { return function () { if (p == settings.nextText) { p = settings.pageIndex + 1; } else if (p == settings.prevText) { p = settings.pageIndex - 1; } if (settings.changPage) { settings.changPage(p); } settings.pageIndex = p; pageDom.Pager(settings); } })(pageIndex)); return dom; } ///将所有的页数全部添加到页面上面, function InitAllPager(dom) { if (settings.showNext && settings.pageIndex != 1) { dom.appendChild(CreatePageDom(settings.prevText)); } for (var i = 1; i <= GetPageCount() ; i++) { dom.appendChild(CreatePageDom(i)); } if (settings.showNext && settings.pageIndex != GetPageCount()) { dom.appendChild(CreatePageDom(settings.nextText)); } } ///添加那省略符号 function AppendOther(dom) { var span = document.createElement('span'); span.innerHTML = '...'; dom.appendChild(span); } ///只添加部分页码到页面上 ///可能 是两边都有省略,也可能有一边省略了一部分 function InitHalfPager(dom) { if (settings.showNext && settings.pageIndex != 1) { dom.appendChild(CreatePageDom(settings.prevText)); } if (settings.pageIndex <= 3) {//前五页和最后 一面 for (var i = 1; i <= 5; i++) { dom.appendChild(CreatePageDom(i)); } AppendOther(dom); dom.appendChild(CreatePageDom(GetPageCount())); } else if (settings.pageIndex >= GetPageCount() - 2) {//最后 五页和第一页 dom.appendChild(CreatePageDom(1)); AppendOther(dom); for (var i = GetPageCount() - 4; i <= GetPageCount() ; i++) { dom.appendChild(CreatePageDom(i)); } } else {//第一页 最后 一页,和中间五页 dom.appendChild(CreatePageDom(1)); if (settings.pageIndex - 3 > 1) { AppendOther(dom); } for (var i = settings.pageIndex - 2; i <= settings.pageIndex + 2; i++) { dom.appendChild(CreatePageDom(i)); } if (settings.pageIndex + 3 < GetPageCount()) { AppendOther(dom); } dom.appendChild(CreatePageDom(GetPageCount())); } if (settings.showNext && settings.pageIndex != GetPageCount()) { dom.appendChild(CreatePageDom(settings.nextText)); } } ///计算总页数 function GetPageCount() { return Math.ceil(settings.total / settings.pageSize); } var pageDom = document.createElement('div'); Element.prototype.Pager = function (option) { pageDom = this; this.innerHTML = ''; for (var i in option) { settings[i] = option[i]; } var total = GetPageCount(); if (total <= 10) { InitAllPager(this); } else { InitHalfPager(this); } }; })(window);