---
title: "仿goolge分页算法"
author: "Doublecqw"
date: "2011-03-18T20:39:46Z"
tags: []
categories: ["Web前端"]
slug: "goolge"
draft: false
lastmod: "2011-03-18T20:39:46Z"
id: 966976
url: "https://doublecqw.iteye.com/blog/966976"
---

下面我们来以最大页数显示6页，开始只显示3页来分析Google分页  
当前页小于4时  
在页数大于6时       没啥好说的  
开始显示  
1 2 3      当前页是1        
1 2 3 4         当前页是2         
1 2 3 4 5   当前页是3         
1 2 3 4 5 6 当前页是4  

小于四中另一种情况 总页数小于当前面的最大索引值  
如：总页数是２　，本页的最大索引值是３  
那么应该显示  
１　２　

当前页大于4时  
当大于4时　总页数够大　没啥好说的  
2 3 4 5 6 7         当前页是5        起始值是2    未页 7  
3 4 5 6 7 8         当前页是6        起始值是3    未页 8  
4 5 6 7 8 9         当前页是7        起始值是4    未页 9  
5 6 7 8 9 10        当前页是8        起始值是5    未页 10

大于四的第二种情况  
最后一页的索引值大于记录总页数并且大于这一页要显示的最大索引值  
最后一页的索引值=总记录数  
这页的开始索引值=这页的总记录数-5

大于四的第三种情况  
最后一页的索引值小于这一页要显示的最大索引值，这种情况中存在这个区期  
google页面中最大显示页/2+1    到   google页面中最大显示页-1 之间  
              这页的开始索引值 = 1  
     这页的结束索引值 = 总记录的面数

整合后的代码如下：

privateintnowpage;// 当前页  
    privateintcountrecord;// 总记录数  
    privateintcountpage;// 总页数  
    privateintpageindex;// 当前页记录开始的位置 (nowpage-1)\*PAGESIZE  
    publicstaticfinalintPAGESIZE = 5;// 每页显示的记录数  
    privateintsumindex = 6;//索引的sum值代表的是 google页面中最大显示页数  
    privateintstartindex;// 开始的索引值  
    privateintendindex;// 结束的索引值

// 计算索引位置  
       if (this.nowpage &lt;= 4) {//当前页小于第四页  
     
this.startindex = 1;  
           this.endindex = this.nowpage + 2;  
//但是第一页显示的页数（endindex）大于了总记录数实际有的页数  
           if(this.endindex&gt;this.countpage){             
                this.endindex=this.countpage;  
           }  
            
       }elseif(this.nowpage&gt;4){ //当前面大于第四页  
           this.startindex=this.nowpage-3;  
           this.endindex=this.nowpage+2;  
//最后一页的索引值大于记录总页数并且大于这一页要显示的最大索引值  
if(this.endindex&gt;this.countpage && this.endindex &gt; this.sumindex){  
              this.endindex=this.countpage;  
              this.startindex=this.countpage-5;  
           }  
//最后一页的索引值小于这一页要显示的最大索引值，这种情况中存在这个区期//sumindex/2+1 到 sumindex-1 之间  
           if(this.endindex &lt; this.sumindex){  
              this.startindex = 1;  
              this.endindex = this.countpage;  
           }  
       }

 

本文原地址：[http://student.csdn.net/space.php?uid=1038661&do=blog&id=56378](http://student.csdn.net/space.php?uid=1038661&do=blog&id=56378)