JavaScript 分页算法
Posted 乱舞春秋__
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript 分页算法相关的知识,希望对你有一定的参考价值。
功能:
1.点击页码,可实现跳转
2.输入页码,可实现跳转
3.点击上一页或下一页可实现跳转
完整代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>分页</title>
<style>
* {
margin: 0;
padding: 0;
}
.box {
margin: 100px 50px;
}
.nav {
display: inline-block;
}
.pageNum {
box-sizing: border-box;
padding: 5px;
width: 30px;
height: 28px;
line-height: 28px;
text-align: center;
}
.pre,
.next,
.go {
width: 46px;
height: 30px;
}
.page {
display: inline-block;
width: 30px;
height: 28px;
line-height: 28px;
border: 1px solid #ccc;
margin-right: 3px;
text-align: center;
list-style: none;
cursor: pointer;
}
.now {
background-color: rgba(135, 207, 235, 0.397);
}
</style>
</head>
<body>
<div class="box">
<button class="pre">上一页</button>
<ul class="nav"></ul>
<button class="next">下一页</button>
<span class="info">页码:</span>
<input type="text" class="pageNum" maxlength="2">
<button class="go">跳转</button>
</div>
<script>
var nav = document.querySelector('.nav');
var pre = document.querySelector('.pre');
var next = document.querySelector('.next');
var go = document.querySelector('.go');
var pageNum = document.querySelector('.pageNum');
var nowPage = 1;
var totalPage = 20;
function changeNum(nowP, totalP) {
var str = '';
for (var i = 1; i <= totalPage; i++) {
if (i == 2 && nowP > 4) {
i = nowP - 2;
str += '<li class = "page">...</li>';
}
else if (i == nowP + 3 && nowP + 3 < totalP) {
i = totalP - 1;
str += '<li class = "page">...</li>';
}
else {
if (i == nowP) {
str += '<li class = "page now clickable">' + i + '</li>';
}
else {
str += '<li class = "page clickable">' + i + '</li>';
}
}
}
nav.innerHTML = str;
}
function getClickableEles() {
var clickableEles = document.getElementsByClassName('clickable');
for (var i = 0; i < clickableEles.length; i++) {
clickableEles[i].addEventListener('click', function () {
nowPage = parseInt(this.innerText);
changeNum(nowPage, totalPage);
getClickableEles();
})
}
}
changeNum(nowPage, totalPage);
getClickableEles();
pre.addEventListener('click', function () {
if (nowPage <= 1) {
return;
}
nowPage--;
changeNum(nowPage, totalPage);
getClickableEles();
});
next.addEventListener('click', function () {
if (nowPage >= totalPage) {
return;
}
nowPage++;
changeNum(nowPage, totalPage);
getClickableEles();
});
go.addEventListener('click', function () {
var num = parseInt(pageNum.value);
if (num) {
nowPage = num;
changeNum(nowPage, totalPage);
}
else {
alert('请输入页码!');
}
getClickableEles();
});
</script>
</body>
</html>
效果图:
当前页码小于等于4时:
当前页码大于4,小于等于16时时:
当前页码大于16时:
以上是关于JavaScript 分页算法的主要内容,如果未能解决你的问题,请参考以下文章
modx - 当我在同上片段中使用“&documents =”参数时,分页不起作用
VSCode自定义代码片段12——JavaScript的Promise对象