纯JS实现前端分页按钮
这个代码是用纯javascript实现分页按钮的基础功能,至于拓展功能大家根据自己的需求拓展就好,这里只展示根据按钮数量和总页数的关系来控制边界的基础算法(写的可能有点长,但是逻辑相对好理解,敬请批评指正)。
防下溢效果:
处于中段效果
防上溢测试效果
具体代码实现(具体思路在代码注释中了):
<!DOCTYPE html>
<html lang="CN">
<head>
<meta charset="UTF-8">
<title>js换页</title>
</head>
<script>
var TOTALBUTTOM = 7;
var totalpage = 12;
pagecontroller = function (page) {
var beginpage, endpage;
var pageno = parseInt(page)
if (totalpage > TOTALBUTTOM) {
if (pageno - parseInt(TOTALBUTTOM / 2) < 1) {
beginpage = 1;
endpage = beginpage + TOTALBUTTOM - 1;
} else {
beginpage = pageno - parseInt(TOTALBUTTOM / 2);
endpage = pageno + parseInt(TOTALBUTTOM / 2);
}
if (endpage >= totalpage) {
endpage = totalpage;
}
if (endpage - pageno < parseInt(TOTALBUTTOM / 2)) {
endpage = totalpage;
beginpage = totalpage - TOTALBUTTOM + 1;
}
else if (pageno - beginpage < parseInt(TOTALBUTTOM / 2)) {
beginpage = 1;
endpage = beginpage + TOTALBUTTOM - 1;
}
else {
beginpage = pageno - parseInt(TOTALBUTTOM / 2);
endpage = pageno + parseInt(TOTALBUTTOM / 2);
}
}
else if (totalpage <= TOTALBUTTOM) {
beginpage = 1;
endpage = totalpage;
}
var html = "";
for (var i = beginpage; i <= endpage; i++) {
html += "<button id='pagebtn' value='" + i + "' onclick =pagecontroller(value)>" + i + "</button>";
}
document.getElementById("pagebtn").innerHTML = html;
document.getElementById("info").innerHTML = "当前第" + pageno + "页<br>第一个按钮是第" + beginpage + "页<br>最后的按钮是第" + endpage + "页" + "<br>共" + totalpage + "页";
}
window.onload = function () {
pagecontroller(1);
}
</script>
<body>
<div id="pagebtn"></div>
<span id="info"></span>
</body>
</html>
敬请批评建议指正!
|