原生js实现分页效果
使用原生js实现分页的效果,逻辑简单,适合新手开发
以下是代码
<!DOCTYPE html>
<html>
<head>
<title>js的分页</title>
<style type="text/css">
ul{list-style: none;}
#con li{
width:200px;
height:30px;
text-align:center;
font-family: 'Microsoft Yahei';
font-size:16px;
margin:0 auto;
border:1px solid #ddd;
}
#pageEnd,#con{
width:400px;
height:130px;
margin:0 auto;
text-align:center;
}
#pageEnd li{
float:left;
}
a{
text-decoration: none;
color:#333;
}
</style>
</head>
<body onload="goPage(1,3);">
<ul id="con">
<li>第1页</li>
<li>第2页</li>
<li>第3页</li>
<li>第4页</li>
<li>第5页</li>
<li>第6页</li>
<li>第7页</li>
<li>第8页</li>
<li>第9页</li>
<li>第10页</li>
<li>第11页</li>
<li>第12页</li>
</ul>
<div id="pageEnd"></div>
<script type="text/javascript">
function goPage(pno,psize){
var pcon = document.getElementById('con');
var num = pcon.getElementsByTagName('li').length;//总的记录数
var pTotal = 0;//总页数
var pageSize = psize;//显示的条数
// 总共分的页数
if(num/pageSize > parseInt(num/pageSize)){
pTotal = parseInt(num/pageSize)+1;
}else{
pTotal = parseInt(num/pageSize);
}
var currentPage = pno;//当前页
var startRow = (currentPage - 1) *pageSize +1;//开始显示的行数
var endRow = currentPage *pageSize;//结束显示的行数
// 循环显示分页
for (var i=1;i<(num+1);i++){
var showC = pcon.getElementsByTagName('li')[i-1];
console.log(showC);
if(i>=startRow && i<=endRow){
showC.style.display = "block";
}else{
showC.style.display = "none";
}
}
// 底部的按钮设置
var endP = document.getElementById('pageEnd');
var temp ="共"+pTotal+"页"+"当前是第"+currentPage+"页";
if(currentPage > 1){
temp += '<a href="#" onclick="goPage('+(1)+','+pageSize+')">首页</a>';
temp += '<a href="#" onclick="goPage('+(currentPage-1)+','+pageSize+')">上一页</a>';
}else{
temp += "首页";
temp += "上一页";
}
// 如果当前页小于总页数可以点击下一页和尾页(假设为current=4)
if(currentPage < pTotal){
temp += '<a href="#" onclick="goPage('+(currentPage+1)+','+pageSize+')">下一页</a>';
temp += '<a href="#" onclick="goPage('+pTotal+','+pageSize+')">尾页</a>';
}else{
temp += "下一页";
temp += "尾页";
}
endP.innerHTML =temp;
}
</script>
</body>
</html>