js实现简单分页导航栏效果

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

js实现简单分页导航栏效果

  2021-04-03 我要评论

最终的效果: 

1. 分页需要的几个重要参数:

总记录条数: totalCount (查数据库)

每页记录数: pageSize  (自己设置)

总页数: totalPageNum  (根据上面的参数计算) 

当前页: currentPageNum (前台传入)

当前页要显示的内容 : List<PageInfo> (查数据库: pageSize和currentPageNum每页的计算起始记录索引  

2. 在html页面中添加分页导航条的<DIV>

<body>
 <!--分页导航条 -->
 <div class="page" id="pag" align="center">
 <!--<a href="javascript:void(0);" onclick="js_method($(this).html())">4</a> -->
 </div>
</body>

3. 编写分页逻辑的js

<script type="text/javascript">
 $(function () { 
 //这里通过ajax查询到总记录数totalCount
 //设定每页显示记录数pageSize,算出总页数totalPageNum
  js_method(1,10);
 });
 /**
 * 传入当前页和和总页数
 */
 function js_method(currentPageNum,totalPageNum) {
 currentPageNum = Number(currentPageNum);
  var startPageNum = currentPageNum - 2; //起始页
  var endPageNum = currentPageNum + 2; //结束页
  $("#pag").text("") //清空导航条
  if (startPageNum <= 0) {
  startPageNum = 1
  endPageNum = startPageNum + 4
  }
  if (endPageNum > totalPageNum) {
  endPageNum = totalPageNum
  startPageNum = endPageNum - 4
  }
 
  if (currentPageNum != 1) {
  $("#pag").append(
 "<a href='javascript:void(0);' onclick='js_method(1,"+totalPageNum+")' >首页</a>"
 )
  $("#pag").append(
  "<a href='javascript:void(0);' onclick='js_method($(\".active\").text()-1,"+totalPageNum+")' id='prePageNum'>«</a>"
 )
  }
  for (var i = 0; i <= endPageNum; i++) {
  if (i >= startPageNum) {
 
   if (i == currentPageNum) {
   var ele = "<a href='javascript:void(0);' class='active' onclick='js_method($(this).text(),"+totalPageNum+")' >" +
    i + "</a>"
   } else {
   var ele = "<a href='javascript:void(0);' onclick='js_method($(this).text(),"+totalPageNum+")' >" + i + "</a>"
   }
  }
  $("#pag").append(ele)
  }
  if (currentPageNum != totalPageNum) {
  $("#pag").append(
   "<a href='javascript:void(0);' onclick='js_method(Number($(\".active\").text())+1,"+totalPageNum+")' id='prePageNum' rel='pre'>»</a>"
  )
 $("#pag").append(
 "<a href='javascript:void(0);' onclick='js_method(10,"+totalPageNum+")' >尾页</a>"
 )
  }
 //在这里通过ajax去查询当前页的数据
 }
 </script>

4. 添加css样式

.page {
 height: 34px;
 line-height: 34px;
 }
.page a {
 display: inline-block;
 border: 1px solid #ededed;
 padding: 0 12px;
 color: #3e3e3e;
 font-size: 14px;
 font-family: tahoma,simsun;
 text-decoration: none;
 }
.page a:hover {
 color: #f40;
 border-color: #f40;
 }
.page .active,.page .active:hover {
 color: #fff;
 background: #f40;
 border: solid 1px #f40;
}
您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们