思路这样,看着有点乱
function Pagination(container, total, current) {
// z总页数
this.total = total;
// 当前页码
this.current = current;
this.html = html;
this.val = val;
this.el = document.createElement("ul"); //TODO: 创建分页组件根节点
if (!this.el) return;
this.el.innerHTML = this.html();
container.appendChild(this.el);
this.el.className = "pagination";
if (this.total <= 1) {
this.el.className = "pagination hide"; //TODO: 判断是否需要隐藏当前元素
}
function html() {
if (this.total <= 1) return "";
//TODO: 生成组件的内部html字符串
const headPage = "<li>首页</li>";
const footerPage = "<li>末页</li>";
let strPage = "";
if (this.total <= 5) {
// 当期总页数小于等于5时候
for (let index = 1; index <= this.total; index++) {
if (index === this.current) {
strPage += `<li class='current'>${index}</li>`;
} else {
strPage += `<li>${index}</li>`;
}
}
return strPage;
} else {
// 当总页数大于5的情况下
if (this.current <= 3) {
// 当前页小于3,由于总页数大于5所以需要显示末页
for (let index = 1; index <= 5; index++) {
if (index === this.current) {
strPage += `<li class='current'>${index}</li>`;
} else {
strPage += `<li>${index}</li>`;
}
}
return strPage + footerPage;
} else {
// 当前页大于3,再分情况
if (this.current + 2 < this.total) {
// 当前页+2小于总页数时,说明后面还有页数,由于current >3 说明前面也有隐藏的,综合需要显示首页和尾页
for (let index = this.current - 2; index <= this.current + 2; index++) {
if (index === this.current) {
strPage += `<li class='current'>${index}</li>`;
} else {
strPage += `<li>${index}</li>`;
}
}
return headPage + strPage + footerPage;
} else {
//当前页数 + 2大于总页数
for (let index = total - 4; index <= this.total; index++) {
if (index === this.current) {
strPage += `<li class='current'>${index}</li>`;
} else {
strPage += `<li>${index}</li>`;
}
}
return headPage + strPage;
}
}
}
}
//通过修改当前页面动态改变当前组件html
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();
}
}
//new Pagination(document.querySelector("#jsContainer"), 10, 8);

京公网安备 11010502036488号