<!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>
<style>
.item {
display: inline-block;
width: 40px;
height: 40px;
background-color: #ccc;
line-height: 40px;
text-align: center;
border-radius: 50%;
margin: 0 10px;
}
.active {
background-color: red;
color: #fff;
}
</style>
</head>
<body>
<ul></ul>
<div class="pageBar"></div>
<script src="../jquery.min.js"></script>
<script>
var total = 0; // 总页数
var page = 10; // 当前页
var pageSize = 20; // 每页多少条数据
get();
function get() {
$.get('http://39.96.88.57:9090/api/www/bang/bang/musicList', {
bangId: 93,
pn: page,
rn: pageSize
}, function (res) {
console.log(res);
$('ul').html('');
res.data.musicList.forEach(item => {
$('ul').append(`<li>${item.name}</li>`);
});
// 计算请求过来之后的总页数
total = Math.ceil(res.data.num / pageSize);
// 渲染分页
render();
})
}
function render() {
$('.pageBar').html('');
var html = '';
html += '<span class="pre">上一页</span>';
// 如果总页数在7个之内,不需要省略号
if (total <= 7) {
for (let i = 0; i < total; i++) {
html += `<span class="item ${i+1 === page ? 'active' : ''}">${i + 1}</span>`;
}
} else { // total > 7
// 只有后面有... 当前页<=4的时候的效果 1 2 3 4 5 6 ...
if (page <= 4) {
for (let i = 0; i < 6; i++) {
html += `<span class="item ${i+1 === page ? 'active' : ''}">${i + 1}</span>`;
}
html += `<span class="item">...</span>`;
html += `<span class="item">${total}</span>`;
} else if (page <= total - 4) { // 前后都有... 当前页<=总页数 - 4 page=15 1...13 14 15 16 17...total
html += `<span class="item">1</span>`;
html += `<span class="item">...</span>`;
for (let i = page - 2; i <= page + 2; i++) {
// [13, 14, 15, 16, 17]
html += `<span class="item ${i === page ? 'active' : ''}">${i}</span>`;
}
html += `<span class="item">...</span>`;
html += `<span class="item">${total}</span>`;
} else { // 只有前面有...
html += `<span class="item">1</span>`;
html += `<span class="item">...</span>`;
for (let i = total - 5; i <= total; i++) {
// total=15 [10, 11, 12, 13, 14, 15]
html += `<span class="item ${i === page ? 'active' : ''}">${i}</span>`;
}
}
}
html += '<span class="next">下一页</span>';
$('.pageBar').append(html);
}
// 上一页
$('.pageBar').on('click', '.pre', function () {
if (page === 1) return;
page--;
get();
})
// 下一页
$('.pageBar').on('click', '.next', function() {
if (page === total) return;
page++;
get();
})
// 点击数字
$('.pageBar').on('click', '.item', function() {
var index = $(this).text() * 1;
if (isNaN(index)) return;
page = index;
get();
})
</script>
</body>
</html>
原生js手搓分页
最新推荐文章于 2024-01-18 01:01:46 发布