以下是一个使用 JavaScript 和 CSS 实现简单分页的示例代码:
HTML 部分:
<!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">
<link rel="stylesheet" href="styles.css">
<title>分页示例</title>
</head>
<body>
<div id="content">
<!-- 这里放置要分页显示的内容 -->
<p>内容 1</p>
<p>内容 2</p>
<p>内容 3</p>
<p>内容 4</p>
<p>内容 5</p>
<p>内容 6</p>
<p>内容 7</p>
<p>内容 8</p>
<p>内容 9</p>
<p>内容 10</p>
<!-- 更多内容... -->
</div>
<div id="pagination">
<!-- 分页按钮将生成在这里 -->
</div>
<script src="script.js"></script>
</body>
</html>
CSS 部分(styles.css):
#pagination {
display: flex;
justify-content: center;
margin-top: 20px;
}
.pagination-button {
padding: 5px 10px;
margin: 0 2px;
border: 1px solid #ccc;
background-color: #f9f9f9;
cursor: pointer;
}
.pagination-button.active {
background-color: #007BFF;
color: white;
border-color: #007BFF;
}
JavaScript 部分(script.js):
const content = document.getElementById('content');
const itemsPerPage = 3; // 每页显示的项数
const totalItems = content.children.length;
const totalPages = Math.ceil(totalItems / itemsPerPage);
const pagination = document.getElementById('pagination');
function showPage(pageNumber) {
const start = (pageNumber - 1) * itemsPerPage;
const end = start + itemsPerPage;
for (let i = 0; i < totalItems; i++) {
content.children[i].style.display = i >= start && i < end? 'block' : 'none';
}
updatePaginationButtons(pageNumber);
}
function createPaginationButtons() {
for (let i = 1; i <= totalPages; i++) {
const button = document.createElement('button');
button.innerText = i;
button.classList.add('pagination-button');
if (i === 1) {
button.classList.add('active');
}
button.addEventListener('click', () => showPage(i));
pagination.appendChild(button);
}
}
function updatePaginationButtons(activePage) {
const buttons = pagination.getElementsByClassName('pagination-button');
for (let i = 0; i < buttons.length; i++) {
buttons[i].classList.remove('active');
if (i + 1 === activePage) {
buttons[i].classList.add('active');
}
}
}
createPaginationButtons();
showPage(1);
基础概念: 分页是将大量的数据或内容分成多个页面进行显示,以提高用户体验和页面加载效率。
优势:
应用场景:
可能出现的问题及解决方法:
希望这个示例对你有帮助!如果还有其他需求,请进一步说明。
领取专属 10元无门槛券
手把手带您无忧上云