如何寫一個簡單的分頁元件(原理)

與自己賽跑的青年發表於2018-12-11

來說說分頁最基本的原理

先研究下element-pagation的分頁展示形式,發現有以下規律,然後就有了以下的程式碼

1,2,3,4,5,6,7
1,2,3,4,5,6,...,8
1,...,3,4,5,6,7,8
1,...,3,4,5,6,...,8
複製程式碼
function showPages(page, total,pagerCount) {
  var str = "" 
  for (var i = 1; i <= total; i++) {
	  if(total > pagerCount){
		  if(total-pagerCount >1){
				var middle = Math.ceil(total/2)
				if(total - page < 4){
					if(i == 2){
					  str =  str + "..." 
					}else if( i > total-6 || i == 1 ){
					 str = str + i +  ""
					}	
				}else if( page < 5 ){
					if(i == total-1){
						str =  str + "..." 
					}else if(i < 7 || i == total){
						str = str + i +  ""
					} 
				}else{
					if(i == total-1){
						str =  str + "..." 
					}else if(i == 2){
						str =  str + "..." 
					}else if(page-2 <= i && i<= page+2){
						str = str + i +  ""
					}else if(i == 1){
						str = str + i +  ""
					}else if(i == total){
						str = str + i +  ""
					}
				}			
		  }else{
				var middle = total/2
				if(page>middle){						
					if(i == 2){
						str =  str + "..." 
					}else{
						str = str + i +  ""
					} 
				}else{	
					if(i == total-1){
					  str =  str + "..." 
					}{	
					  str = str + i +  ""
					}		
				}		
		  }
      }else{
		str = str +   "" + i
      }
  }
  return str
}
var total = 11
for (var i = 1; i <= total; i++) {
  var ret = showPages(i, total,7)
  console.log(ret)
}
複製程式碼

相關文章