javascript實現的數字分頁效果程式碼例項

螞蟻小編發表於2017-03-16

現在很多網站都有使用數字分頁效果,這當然是有原因的,因為數字分頁更為清晰,導航效果更為方便,下面就是一段這樣的程式碼例項,希望能夠給需要的朋友帶來一定的幫助。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
.page{margin:2em;}
.page a{
  text-decoration:none;
  display:inline-block;
  line-height:14px;
  padding:2px 5px;
  color:#333;
  border:1px solid #ccc;
  margin:0 2px;
}
.page a:hover, .page a.on{
  background:#999;
  color:#fff;
  border:1px solid #333;
}
.page a.unclick, .page a.unclick:hover{
  background:none;
  border:1px solid #eee;
  color:#999;
  cursor:default;
}
</style>
<script type="text/javascript">
function setPage(container, count, pageindex){
  var container = container;
  var count = count;
  var pageindex = pageindex;
  var a = [];
  if (pageindex == 1){
    a[a.length] = "<a href=\"#\" class=\"prev unclick\">prev</a>";
  } 
  else{
    a[a.length] = "<a href=\"#\" class=\"prev\">prev</a>";
  }
  function setPageList(){
    if (pageindex == i){
      a[a.length] = "<a href=\"#\" class=\"on\">" + i + "</a>";
    } 
    else{
      a[a.length] = "<a href=\"#\">" + i + "</a>";
    }
  }
  if (count <= 10){
    for (var i = 1; i <= count; i++){
      setPageList();
    }
  }
  else 
  {
    if (pageindex <= 4){
      for (var i = 1; i <= 5; i++){
        setPageList();
      }
      a[a.length] = "...<a href=\"#\">" + count + "</a>";
    } 
    else if (pageindex >= count - 3){
      a[a.length] = "<a href=\"#\">1</a>...";
      for (var i = count - 4; i <= count; i++){
        setPageList();
      }
    }
    else{ 
      a[a.length] = "<a href=\"#\">1</a>...";
      for (var i = pageindex - 2; i <= pageindex + 2; i++){
        setPageList();
      }
      a[a.length] = "...<a href=\"#\">" + count + "</a>";
    }
  }
  if (pageindex == count){
    a[a.length] = "<a href=\"#\" class=\"next unclick\">next</a>";
  } 
  else{
    a[a.length] = "<a href=\"#\" class=\"next\">next</a>";
  }
  container.innerHTML = a.join("");
  var pageClick = function(){
    var oAlink = container.getElementsByTagName("a");
    var inx = pageindex;
    oAlink[0].onclick = function(){ 
      if (inx == 1){
        return false;
      }
      inx--;
      setPage(container, count, inx);
      return false;
    }
    for (var i = 1; i < oAlink.length - 1; i++){ 
      oAlink[i].onclick = function(){
        inx = parseInt(this.innerHTML);
        setPage(container, count, inx);
        return false;
      }
    }
    oAlink[oAlink.length - 1].onclick = function(){ 
      if (inx == count){
        return false;
      }
      inx++;
      setPage(container, count, inx);
      return false;
    }
  }()
}
window.onload=function(){
  setPage(document.getElementsByTagName("div")[0],10,1);
  setPage(document.getElementsByTagName("div")[1],13,6);
}
</script>
</head>
<body>
<div class="page"></div>
<div class="page"></div>
</body>
</html>

相關文章