<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style>
a{ margin:5px;}
</style>
<script>
window.onload = function(){
page({
id : 'div1',
nowNum : 7,
allNum : 30,
callBack : function(now,all){
alert('当前页:' + now +',总共页:'+all);
}
});
};
function page(opt){
if(!opt.id){return false};
var obj = document.getElementById(opt.id);
var nowNum = opt.nowNum || 1;
var allNum = opt.allNum || 5;
var callBack = opt.callBack || function(){};
//首页
if( nowNum>=4 && allNum>=6 ){
var oA = document.createElement('a');
oA.href = '#1';
oA.innerHTML = '首页';
obj.appendChild(oA);
}
//上一页
if(nowNum>=2){
var oA = document.createElement('a');
oA.href = '#' + (nowNum - 1);
oA.innerHTML = '上一页';
obj.appendChild(oA);
}
if(allNum<=5){
for(var i=1;i<=allNum;i++){
var oA = document.createElement('a');
oA.href = '#' + i;
if(nowNum == i){
oA.innerHTML = i;
}
else{
oA.innerHTML = '['+ i +']';
}
obj.appendChild(oA);
}
}
else{
for(var i=1;i<=5;i++){
var oA = document.createElement('a');
if(nowNum == 1 || nowNum == 2){
oA.href = '#' + i;
if(nowNum == i){
oA.innerHTML = i;
}
else{
oA.innerHTML = '['+ i +']';
}
}
else if( (allNum - nowNum) == 0 || (allNum - nowNum) == 1 ){
oA.href = '#' + (allNum - 5 + i);
if((allNum - nowNum) == 0 && i==5){
oA.innerHTML = (allNum - 5 + i);
}
else if((allNum - nowNum) == 1 && i==4){
oA.innerHTML = (allNum - 5 + i);
}
else{
oA.innerHTML = '['+ (allNum - 5 + i) +']';
}
}
else{
oA.href = '#' + (nowNum - 3 + i);
if(i==3){
oA.innerHTML = (nowNum - 3 + i);
}
else{
oA.innerHTML = '['+ (nowNum - 3 + i) +']';
}
}
obj.appendChild(oA);
}
}
//下一页
if( (allNum - nowNum) >= 1 ){
var oA = document.createElement('a');
oA.href = '#' + (nowNum + 1);
oA.innerHTML = '下一页';
obj.appendChild(oA);
}
//尾页
if( (allNum - nowNum) >= 3 && allNum>=6 ){
var oA = document.createElement('a');
oA.href = '#' + allNum;
oA.innerHTML = '尾页';
obj.appendChild(oA);
}
//回调函数
callBack(nowNum,allNum);
var aA = obj.getElementsByTagName('a');
//添加 点击 控制每页
for(var i=0;i<aA.length;i++){
aA[i].onclick = function(){
var nowNum = parseInt(this.getAttribute('href').substring(1));
obj.innerHTML = '';
page({
id : opt.id,
nowNum : nowNum,
allNum : allNum,
callBack : callBack
});
//阻止页码默认
return false;
};
}
}
</script>
</head>
<body>
<div id="div1">
<!--<a href="#1">首页</a>
<a href="#3">上一页</a>
<a href="#2">[2]</a>
<a href="#3">[3]</a>
<a href="#4">4</a>
<a href="#5">[5]</a>
<a href="#6">[6]</a>
<a href="#5">下一页</a>
<a href="#10">尾页</a>-->
</div>
</body>
</html>