前言
最近做的事情偏前端,后台查询好分页数据,前端进行分页,先来观察一下实现。以网易云pc某一首歌的评论为例吧(懒得打开项目了)。
分析
可以看到当前页是 第8页 显示的页号范围是当前页-3 和 当前页+3 必要时额外显示箭头和第一页最后一页 超过一定距离显示成省略号
模拟实现
private static int length = 6 ;
private static int ignoreLength = 1 ;
private static int half = length / 2 ;
根据当前页号,和总页数来计算出开始页号和结束页号。
int begin = pageNo-half;
int end = pageNo + half;
pageNo=pageNo<1 ?1 :pageNo;
if (begin < 1 ){
begin = 1 ;
end = begin + length;
}
if (end >total){
end = total;
begin = total - length;
}
end =total==0 ?1 :end ;
begin = begin <1 ?1 :begin ;
if (pageNo !=1 ){
System.out .print("首页" );
System.out .print(" 上一页 " );
}
if (begin - 1 > ignoreLength){
System.out .print("【1】" );
System.out .print(" ... " );
}
for (int j=begin;j<=end;j++){
if (j == pageNo){
System.out .print( " [" +j+"] " );
}else {
System.out .print( j+" " );
}
}
if (total - end > ignoreLength){
System.out .print(" ... " );
}
if (end < total){
System.out .print("【" +total+"】" );
}
if (pageNo != end){
System.out .print(" 下一页" );
System.out .print(" 末页" );
}
1-10页的效果
聪明的你一定知道,System.out输出的地方换成html就是前端效果啦