当前位置:Gxlcms > JavaScript > js实现简单分页导航栏效果

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

时间:2021-07-01 10:21:17 帮助过:7人阅读

本文实例为大家分享了js实现分页导航栏效果的具体代码,供大家参考,具体内容如下

最终的效果: 

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;
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

人气教程排行