<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<style type="text/css">
#page-base {display: flex;align-items: center;height: 1.85rem;justify-content: center;}
#page-base button,#page-base div {margin-right: 0.45rem;border: none;border: 1px solid #E6E6E6;line-height: 1.7rem;min-width: 1.7rem;text-align: center;outline: 0;display: inline-block;color: #828F98!important;background: none}
#page-base div{color: #333!important;height: 100%;line-height: 1.85rem;}
</style>
</head>
<body>
<div id="page-base"></div>
<script type="text/javascript">
class Page {
constructor(index, size, target, callback) {
//保存数据
this.index = index;
this.size = size;
this.target = target;
this.callback = callback;
//画
this.repaint(this.index, this.size);
//保存this指向
let that = this;
//绑定事件
that.target.onclick = function(e) {
let index = e.target.innerHTML;
//处理跳转
if (index === "上一页") {
that.pageTo(that.index - 1);
} else if (index === "下一页") {
that.pageTo(that.index + 1);
} else if (+index) {
//当前页不翻页
if (+index != that.index) {
that.pageTo(+index);
}
}
}
}
//画
repaint(newIndex, newSize) {
//刷新参数
this.index = newIndex;
this.size = newSize;
//清空内容
this.target.innerHTML = "";
//获取元素数组信息
let info = hasItem(this.index, this.size);
//遍历之
for (let i = 0; i < info.length; i++) {
//忽略null
if (info[i] == null) {
continue;
}
if (info[i] != this.index + "") {
this.target.appendChild(createTag("button", info[i]));
} else {
// 如果是当前选中的,那么就追加成div(方便给选中的页码加样式)
this.target.appendChild(createTag("div", info[i]));
}
}
return this;
//判断有哪些元素,null表示没有
function hasItem(index, size) {
let result = [];
//上一页下一页
result[0] = (index == 1) ? null : "上一页";
result[10] = (index == size) ? null : "下一页";
//首页尾页
result[1] = "1";
result[9] = size + "";
//省略号
result[2] = (index - 2 >= 3) ? "..." : null;
result[8] = (index + 2 <= size - 2) ? "..." : null;
//中间五个
result[3] = (index - 2 >= 2) ? index - 2 : null;
result[4] = (index - 2 >= 1) ? index - 1 : null;
result[5] = (index != 1 && index != size) ? index : null;
result[6] = (index + 2 <= size) ? index + 1 : null;
result[7] = (index + 2 <= size - 1) ? index + 2 : null;
return result;
}
//创建元素
function createTag(tagName, data, checked) {
let tag = document.createElement(tagName);
tag.innerHTML = data;
return tag;
}
}
//翻页
pageTo(newIndex) {
this.callback(newIndex);
this.repaint(newIndex, this.size);
return this;
}
}
</script>
<script type="text/javascript">
const target = document.getElementById("page-base");
const page = new Page(1, 10, target, function(index) {
// console.log("翻到第" + index + "页");
list(index)
});
function list(index){
console.log(index,'----')
}
</script>
</body>
</html>
js 翻页 插件
最新推荐文章于 2023-02-16 10:49:07 发布