我要做一个数字分页的效果,如图
这是我目前的代码,用了最笨的方法:分情况讨论
public Lists:any = []; defaultPage() { this.updatePageList(); this.Lists.startLists = [];//这个是'...'左边的数组[1,2,3]或者[1,2] this.Lists.endLists = [];//这是最右边的[11,12] this.Lists.midLists = [];//这是中间显示的数组 if (this.pageCount < 7) { this.Lists.spanStatus = [false, false];//这个是`...`的状态,false就不显示 for (let i = 0; i < this.pageCount; i++) {//pageCount是总页码,currentPageNum是当前页码 this.Lists.startLists.push(i + 1); } } else if (this.pageCount >= 7) { this.Lists.spanStatus = [true, false]; for (let i = 0; i < 3; i++) { this.Lists.startLists.push(i + 1); } for (let j = this.pageCount - 3; j < this.pageCount; j++) { this.Lists.endLists.push(j + 1); } } //页码 let midEndNumber; if (this.currentPageNum == 3 ) { midEndNumber = this.pageCount >= 4 ? 4 : this.pageCount; this.Lists.midLists = [midEndNumber]; this.Lists.spanStatus[0] = false; if(this.pageCount>=7){ this.Lists.spanStatus[1]=true; this.Lists.endLists=[this.pageCount-1,this.pageCount]; }else{ this.Lists.spanStatus[1]=false; } } if (this.currentPageNum > 3 && this.currentPageNum < 5) { midEndNumber = this.pageCount >= this.currentPageNum + 2 ? this.currentPageNum + 2 : this.pageCount; for (let i = 4; i < midEndNumber; i++) { this.Lists.midLists.push(i); this.Lists.spanStatus[0] = false; } if(this.pageCount>=7){ this.Lists.spanStatus[1]=true; this.Lists.endLists=[this.pageCount-1,this.pageCount]; }else{ this.Lists.spanStatus[1]=false; } } if (this.currentPageNum >= 5) { midEndNumber = this.pageCount >= this.currentPageNum + 2 ? this.currentPageNum + 2 : this.pageCount; for (let i = this.currentPageNum - 1; i < midEndNumber; i++) { this.Lists.midLists.push(i); } this.Lists.spanStatus[0] = true; this.Lists.startLists=[1,2]; if(this.pageCount>=7){ this.Lists.spanStatus[1]=true; this.Lists.endLists=[this.pageCount-1,this.pageCount]; }else{ this.Lists.spanStatus[1]=false; } } return this.Lists; }
我觉得这个方法太笨了,写不下去了,求大神求简便算法
从当前页码出发思考。
...
与当前页码的前后距离永远是 2前2个页码(1、2)与最后2个页码(图中是11、12,实际需要从length计算)是永远不会变成
...
的...
省略的数值是可以根据当前页码算出来的,前是:2 到 cur - 1
,后是cur+1 到 length -2
。如果之间的距离为 0,那就是没有省略号。补充:
此时计算省略的数值范围变成
cur+1 到 length -3
或3 到 cur - 1
,也就是前后不变码变成3个。