话不多少,直接上代码
html代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>javascript分页效果</title>
<style>
a{margin-right:5px;}
</style>
</head>
<body>
<div id="div1">
</div>
<script src="js/myPage.js"></script>
</body>
</html>
javascript代码:
window.onload = function() {
var page = new Page({
'id': 'div1',
'allNum': 10,
'showNum': 5,
'nowNum': 10,
'callback':function(nowIndex,allIndex){
alert('当前页'+nowIndex+',总页数'+allIndex);
}
});
page.init();
}
//采用面向对象的方法进行封装
function Page(opt) {
if (!opt) {
return;
}
this.id = opt.id;
this.oParent = document.getElementById(this.id);
//一共有多少页
this.allNum = opt.allNum || 5;
//显示多少个分页
this.showNum = opt.showNum || 5;
//当前选择的页面
this.nowNum = opt.nowNum || 1;
this.callback=opt.callback||function(){};
}
Page.prototype = {
constructor: Page,
init: function() {
var that = this;
this.change(1);
},
change: function(curNum) {
this.nowNum = curNum;
//为了提高性能,可以移除原来所有链接的事件处理程序
var aAs = this.oParent.getElementsByTagName('a');
for (var i = 0; i < aAs.length; i++) {
aAs[i].onclick = null;
}
this.oParent.innerHTML = '';
var tmp = Math.floor(this.showNum / 2);
//处理首页,当nowNum>tmp+1,并且allNum>showNum时显示
if (this.nowNum > tmp + 1 && this.allNum > this.showNum) {
this.appendLink('#1', '首页');
}
//处理上一页,只要当前选择页不是首页,就呈现
if (this.nowNum > 1) {
this.appendLink('#' + (this.nowNum - 1), '上一页');
}
//处理中间页码
//如果总页码小于显示页码数,从1开始以此显示
if (this.allNum <= this.showNum) {
this.appendPageLinks(1, this.allNum);
} else {
//如果选择的是第1页到第tmp页,显示前面showNumge
if (this.nowNum <= tmp) {
this.appendPageLinks(1, this.showNum);
}
//如果选择是第this.allNum-tmp,显示最后showNum个
else if (this.nowNum >= this.allNum - tmp) {
this.appendPageLinks(this.allNum - this.showNum + 1, this.allNum);
}
//其他情况,则以this.nowNum为中心,显示this.showNum个
else {
this.appendPageLinks(this.nowNum - tmp, this.nowNum + tmp);
}
}
//处理下一页,只要当前选择的不是最后一页,就显示下一页
if (this.nowNum < this.allNum) {
this.appendLink('#' + (this.nowNum + 1), '下一页');
}
//处理最后一页,当nowNum<this.allNum-tmp,并且allNum>showNum时候显示
if (this.nowNum < this.allNum - tmp & this.allNum > this.showNum) {
this.appendLink('#' + this.allNum, '尾页');
}
//添加事件处理程序
var that = this;
var aAs = this.oParent.getElementsByTagName('a');
for (var i = 0; i < aAs.length; i++) {
aAs[i].onclick = function() {
var index = parseInt(this.getAttribute('href').substring(1));
that.change(index);
that.callback(that.nowNum,that.allNum);
return false;
}
}
},
appendLink: function(href, innerHtml) {
var oA = document.createElement('a');
oA.href = href;
oA.innerHTML = innerHtml;
this.oParent.appendChild(oA);
},
appendPageLink: function(pageNum) {
if (pageNum === this.nowNum) {
this.appendLink('#' + pageNum, pageNum);
} else {
this.appendLink('#' + pageNum, '[' + pageNum + ']');
}
},
appendPageLinks: function(startPageNum, endPageNum) {
for (var i = startPageNum; i <= endPageNum; i++) {
this.appendPageLink(i);
}
}
}