在前端展示页面列表时,下方会有分页控件,当列表数量比较多时,我们希望在分页控件中加入省略号以方便页面展示,下面基于Bootstrap的pagination来实现这一功能。
/**
* 获取分页
* @param totalPage 页码总量
* @param currentPage 当前页码
* @returns {String}
*/
function getPagination(totalPage, currentPage){
var paginationInfo = "<ul class=\"pagination\" >"+
"<li><a href=\"javascript:void(0);\" " +
" οnclick=\"refreshPages("+totalPage+" , "+(currentPage-1)+
")\""+">«</a></li>";
if(totalPage<=10){
for(var i=1; i<=totalPage; i++){
paginationInfo += "<li><a href=\"javascript:void(0);\" " +
" οnclick=\"refreshPages("+totalPage+" , "+i+")\">"+i+"</a></li>";
}
}
else{
if(currentPage<=3){
for(var i=1; i<=currentPage+2; i++){
paginationInfo += "<li><a href=\"javascript:void(0);\" " +
" οnclick=\"refreshPages("+totalPage+" , "+i+")\">"+i+"</a></li>";
}
paginationInfo += "<li><a href=\"#\">...</a></li>";
paginationInfo += "<li><a href=\"javascript:void(0);\" " +
" οnclick=\"refreshPages("+totalPage+" , "+totalPage")\">"+totalPage+"</a></li>";
}else if(currentPage<=totalPage-5){
paginationInfo += "<li><a href=\"javascript:void(0);\" " +
" οnclick=\"refreshPages("+totalPage+" , "+1+")\">"+1+"</a></li>";
paginationInfo += "<li><a href=\"#\">...</a></li>";
for(var i=currentPage-1; i<=currentPage+2; i++){
paginationInfo += "<li><a href=\"javascript:void(0);\" " +
" οnclick=\"refreshPages("+totalPage+" , "+i+")\">"+i+"</a></li>";
}
paginationInfo += "<li><a href=\"#\">...</a></li>";
paginationInfo += "<li><a href=\"javascript:void(0);\" " +
" οnclick=\"refreshPages("+totalPage+" , "+totalPage+")\">"+totalPage+"</a></li>";
}else{
paginationInfo += "<li><a href=\"javascript:void(0);\" " +
" οnclick=\"refreshPages("+totalPage+" , "+1+")\">"+1+"</a></li>";
paginationInfo += "<li><a href=\"#\">...</a></li>";
for(var i=currentPage-1; i<=totalPage; i++){
paginationInfo += "<li><a href=\"javascript:void(0);\" " +
" οnclick=\"refreshPages("+totalPage+" , "+i+")\">"+i+"</a></li>";
}
}
}
paginationInfo += "<li><a href=\"javascript:void(0);\" " +
" οnclick=\"refreshPages("+totalPage+" , "+(currentPage+1)+")\""+">»</a></li>";
return paginationInfo;
}
getPagination函数的作用是根据页码总数与当前页确定分页的样式,当总页数小于10时,不用加省略号;否则,根据当前页与总页码的相对关系决定如何添加省略号。
function refreshPages(totalPage, currentPage){
if(currentPage<1 || currentPage>totalPage){
return;
}
var paginationInfo = getPagination(totalPage, currentPage);
document.getElementById('pagination').innerHTML=paginationInfo;
}
分页的每一个页调用refreshPages函数用来刷新页码。
最终的效果如图所示: