这是一个仿照谷歌中的分页:
if(this.countpage>=6){
if (this.nowpage <= 4) {
this.startindex = 1;
this.endindex = this.nowpage + 2;
if(this.endindex>this.countpage){
this.endindex=this.countpage;
}
}else if(this.nowpage>4){
this.startindex=this.nowpage-3;
this.endindex=this.nowpage+2;
if(this.endindex>this.countpage){
this.endindex=this.countpage;
this.startindex=this.countpage-5;
}
}else{
this.startindex=1;
if(this.endindex>this.countpage){
this.endindex=this.countpage;
}else{
this.endindex=this.nowpage+2;
}
}
分析:以下是以显示6个数页 为参考
1 2 3 当前页是1 1 2 3
1 2 3 4 当前页是2 起始值1 未页 4
1 2 3 4 5 当前页是3 起始值1 未页 5
1 2 3 4 5 6 当前页是4 起始值1 未页 6
从上图得知 当前页小于等于4时 起始页为1 末页=当前页+2
startindex=1;
endindex=nowpage+2;
注意: 求和值后的endindex 如果endindex大于总页数
那么: this.endindex=this.countpage;
java的实现代码如下:
if (this.nowpage <= 4) { //判断小于等于4的情况
this.startindex = 1;
this.endindex = this.nowpage + 2;
if(this.endindex>this.countpage){
this.endindex=this.countpage;
}
}
当大于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
从上图得知 当前页大于4时
1.当前页与尾页的差少于2 开始所以与当前页 差3
endindex=nowpage+2;
startindex=nowapge-3;
注意:求和值后的endindex,如果endindex大于总页数
this.endindex=this.countpage;
this.startindex=this.countpage-5;
java实现代码如下:
if(this.nowpage>4){ //大于4的情况
this.startindex=this.nowpage-3;
this.endindex=this.nowpage+2;
if(this.endindex>this.countpage){
this.endindex=this.countpage;
this.startindex=this.countpage-5;
}
整合后的代码如下:
// 计算索引位置
if (this.nowpage <= 4) { //判断小于等于4的情况
this.startindex = 1;
this.endindex = this.nowpage + 2;
if(this.endindex>this.countpage){
this.endindex=this.countpage;
}
}else if(this.nowpage>4){ //大于4的情况
this.startindex=this.nowpage-3;
this.endindex=this.nowpage+2;
if(this.endindex>this.countpage){
this.endindex=this.countpage;
this.startindex=this.countpage-5;
}
}