用js实现翻页
使用 JavaScript 实现翻页功能
翻页功能通常用于分页显示数据,以下是几种常见的实现方法。
基础翻页逻辑
通过计算当前页码和每页显示的数据量,动态渲染内容。
let currentPage = 1;
const itemsPerPage = 5;
const data = [...]; // 你的数据数组
function renderPage(page) {
const start = (page - 1) * itemsPerPage;
const end = start + itemsPerPage;
const pageData = data.slice(start, end);
// 渲染 pageData 到页面
console.log(pageData);
}
function nextPage() {
if (currentPage * itemsPerPage < data.length) {
currentPage++;
renderPage(currentPage);
}
}
function prevPage() {
if (currentPage > 1) {
currentPage--;
renderPage(currentPage);
}
}
动态生成分页按钮
根据数据总量动态生成分页按钮,并绑定点击事件。
function createPagination() {
const totalPages = Math.ceil(data.length / itemsPerPage);
const pagination = document.getElementById('pagination');
pagination.innerHTML = '';
for (let i = 1; i <= totalPages; i++) {
const btn = document.createElement('button');
btn.textContent = i;
btn.addEventListener('click', () => {
currentPage = i;
renderPage(currentPage);
});
pagination.appendChild(btn);
}
}
带省略号的高级分页
对于大量数据,可以显示部分页码并用省略号表示隐藏的页码。
function createSmartPagination() {
const totalPages = Math.ceil(data.length / itemsPerPage);
const pagination = document.getElementById('pagination');
pagination.innerHTML = '';
// 总是显示第一页
addPageButton(1);
if (currentPage > 3) {
pagination.appendChild(document.createTextNode('...'));
}
// 显示当前页附近的页码
const start = Math.max(2, currentPage - 1);
const end = Math.min(totalPages - 1, currentPage + 1);
for (let i = start; i <= end; i++) {
addPageButton(i);
}
if (currentPage < totalPages - 2) {
pagination.appendChild(document.createTextNode('...'));
}
// 总是显示最后一页
if (totalPages > 1) {
addPageButton(totalPages);
}
}
function addPageButton(page) {
const btn = document.createElement('button');
btn.textContent = page;
if (page === currentPage) {
btn.classList.add('active');
}
btn.addEventListener('click', () => {
currentPage = page;
renderPage(currentPage);
createSmartPagination();
});
pagination.appendChild(btn);
}
无限滚动翻页
当用户滚动到页面底部时自动加载下一页内容。
window.addEventListener('scroll', () => {
if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 500) {
if (currentPage * itemsPerPage < data.length) {
currentPage++;
renderPage(currentPage);
}
}
});
使用 History API 的翻页
实现翻页时同时更新浏览器历史记录。
function changePage(page) {
currentPage = page;
renderPage(currentPage);
window.history.pushState({page}, `Page ${page}`, `?page=${page}`);
}
window.addEventListener('popstate', (event) => {
if (event.state?.page) {
currentPage = event.state.page;
renderPage(currentPage);
}
});
这些方法可以根据具体需求选择或组合使用,实现不同风格的翻页功能。







