效果如下:
代码如下:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
第<span id="pagingText"></span>页,共<span id="total">40</span>页
<div id="pagingDiv"></div>
</body>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
var total = $('#total').html();
//一进页面默认第1页
pagingConstruct(1);
//点击页数
$("#pagingDiv").on('click','a',function(){
var text = $(this).html();
pagingConstruct(parseInt(text));
})
function pagingConstruct(paging){
$('#pagingText').html(paging)
var pagingDivInnerHTML = "";
var isHiddenExist = 0;//这里是加载省略号的flag
//从第1页读到第40页。
for (var i = 1; i <= total; i++) {
if (i == paging) {//如果读到当前页,就仅仅加载一个文本,不放a链接
pagingDivInnerHTML += i + " ";
}else {
//如果是页首,中间页,页尾,当前页的前后三页则不省略。
if (i < 4 || i < (paging + 3) && i > (paging - 3) || i > (total / 2 - 2) && i < (total / 2 + 2) || i > (total - 3)) {
pagingDivInnerHTML += "<a href='javascript:void(0)' >" + i + "</a> ";
isHiddenExist = 0;
}else {//否则就构造...
if (isHiddenExist == 0) {
pagingDivInnerHTML += "...";
isHiddenExist = 1;
}
}
}
}
//把构造的内容放上去pagingDiv
$("#pagingDiv").html(pagingDivInnerHTML);
}
</script>
</html>