JavaScript 页面居中分页算法
有时候页数过多,比如几十上百,会造成页面不好显示,用这个算法可以实现 只显示当前页左右两边 相关的几个页码。
类似element-ui
的这种效果:
javascript
function getPageRange(pageCount, limit, current) {
// 分偶数和奇数
current = parseInt(current)
pageCount = parseInt(pageCount)
limit = parseInt(limit)
let fore = 0, after = 0;
if (limit % 2 == 0) {
fore = parseInt((limit - 1) / 2)
after = parseInt(limit / 2)
}
else {
fore = parseInt(limit / 2)
after = Math.ceil((limit - 1) / 2)
}
let start = current - fore
let end = current + after
if (start < 1) {
if (start == 0) {
start = 1
end += 1
} else {
end += parseInt(Math.abs(start))
if (start < 0) {
end += 1
}
start = 1
}
}
if (end > pageCount) {
start -= end - pageCount
end = pageCount
}
if (start < 1) {
start = 1
}
if (end > pageCount) {
end = pageCount
}
return { star: start, end }
}
let r = getPageRange(36, 5, 3)
console.log(r)
function getPageRange(pageCount, limit, current) {
// 分偶数和奇数
current = parseInt(current)
pageCount = parseInt(pageCount)
limit = parseInt(limit)
let fore = 0, after = 0;
if (limit % 2 == 0) {
fore = parseInt((limit - 1) / 2)
after = parseInt(limit / 2)
}
else {
fore = parseInt(limit / 2)
after = Math.ceil((limit - 1) / 2)
}
let start = current - fore
let end = current + after
if (start < 1) {
if (start == 0) {
start = 1
end += 1
} else {
end += parseInt(Math.abs(start))
if (start < 0) {
end += 1
}
start = 1
}
}
if (end > pageCount) {
start -= end - pageCount
end = pageCount
}
if (start < 1) {
start = 1
}
if (end > pageCount) {
end = pageCount
}
return { star: start, end }
}
let r = getPageRange(36, 5, 3)
console.log(r)