题解 | #分页#
分页
https://www.nowcoder.com/practice/71da71df9d1c4af9b8dc056213473ba7
// current左右两边加起来5页, 一边不足2页的补到另外一边
// 补完仍然到边界的显示 首页 末页
function Pagination(container, total, current) { this.total = total; this.current = current; this.html = html; this.val = val; let ul = document.createElement('ul') this.el = ul; //TODO: 创建分页组件根节点 if (!this.el) return; this.el.innerHTML = this.html(); container.innerHTML = ''; // 额外加的:去除内容 container.appendChild(this.el); this.el.className = 'pagination' +(this.total <= 1 ? ' hide' : ''); //TODO: 判断是否需要隐藏当前元素 function html() { if (this.total <= 1) return ''; //TODO: 生成组件的内部html字符串 // current左右两边加起来5页, 一边不足2页的补到另外一边 // 补完仍然到边界的显示 首页 末页 let left = this.current -2 <= 0 ? 1 : this.current -2 // 左边的页码开始 let left_add // 补完后的页码 let right = this.current + 2 > this.total ? this.total : this.current+2 // 右边的页码结束 let right_add // 补完后的页码 if(left === 1) { let right_2 = 2-(this.current-left)// 左边不够2补到右边的内容 let right_sum = right + right_2// 加完补的之后 right_add = right_sum > this.total ? this.total : right_sum } else { right_add = right } if(right === this.total) { let left_2 = 2 - (this.total -this.current)// 右边不够2补到左边的内容 let left_sum = left - left_2 // 剪完补的之后 left_add = left_sum <= 0 ? 1 : left_sum } else { left_add = left } // 输出页码到page_list中 let page_list = [this.current] console.log(left_add) console.log(right_add) for(let i=this.current-1; i>=left_add; i--) { page_list.unshift(i) } if(left_add > 1) { page_list.unshift('首页') } for(let i=this.current + 1; i<= right_add; i++) { page_list.push(i) } if(right_add < this.total) { page_list.push('末页') } let str = '' page_list.forEach(i => { if(i=== this.current) { str += `<li class="current">${i}</li>` } else { str += `<li>${i}</li>` } }) return str; } function val(current) { if (arguments.length === 0) return this.current; if (current < 1 || current > this.total || current === this.current) return; this.current = current; this.el.innerHTML = this.html(); }; }