<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function f(total, size, page, btnCount = 5) {
const arr = [] // 能看到的页码集合
const num = Math.ceil(total / size) // 页码数
const count = Math.floor(btnCount / 2)//左右要展示几条数据
// 如果页码数小于等于btnCount
if (num <= btnCount) {
for (let i = 1; i <= num; i++) {
arr.push(i)
}
}
if (page > count && page < num - count) {
for (let i = page - count; i < page - count + btnCount; i++) {
arr.push(i)
}
} else if (page <= count) {
for (let i = 1; i < 1 + btnCount; i++) {
arr.push(i)
}
} else if (page >= num - count) {
for (let i = num; i > btnCount; i--) {
arr.push(i)
}
}
return arr
}
console.log(f(100, 10, 1, 5)) // ==> [1, 2, 3, 4, 5]
console.log(f(100, 10, 11, 5)) // ==> [5, 6, 7, 8, 9]
console.log(f(100, 10, 2, 5)) // ==> [1, 2, 3, 4, 5]
console.log(f(100, 10, 5, 5)) // ==> [3, 4, 5, 6, 7]
</script>
</body>
</html>
结果: