無需後端分頁,純前端通過容器高度計算實現長文分頁。本文提供 ThinkPHP 模板結合原生 JS 的完整實現,適合靜態內容展示場景。
height: 700px; overflow: hiddenscrollHeight (內容總高) 與 offsetHeight (可視高)Math.ceil(scrollHeight / offsetHeight)scrollTop = (page-1) * offsetHeight<div id="showContent">{$article.content|htmlspecialchars_decode}</div>
<div id="articlePages"></div>
#showContent {
color: #333;
font-size: 16px;
line-height: 1.6;
height: 700px; /* 固定可視高度 */
overflow: hidden; /* 隱藏溢出,通過 scrollTop 控制顯示區域 */
}
#articlePages {
text-align: right;
margin-top: 10px;
}
#articlePages a {
display: inline-block;
padding: 5px 10px;
margin: 0 3px;
background: #f0f0f0;
border-radius: 3px;
text-decoration: none;
color: #333;
}
#articlePages a:hover { background: #007bff; color: #fff; }
<script>
window.onload = function() {
var content = document.getElementById('showContent');
var pages = document.getElementById('articlePages');
// 計算總頁數
var pageHeight = content.offsetHeight; // 700px
var totalHeight = content.scrollHeight; // 內容實際高度
var totalPages = Math.ceil(totalHeight / pageHeight);
// 生成頁碼鏈接
pages.innerHTML = '共 ' + totalPages + ' 頁 ';
for (var i = 1; i <= totalPages; i++) {
pages.innerHTML += '<a href="javascript:showPage(' + i + ');">' + i + '</a> ';
}
// 翻頁函數
window.showPage = function(pageIndex) {
content.scrollTop = (pageIndex - 1) * pageHeight;
};
};
</script>
resize 重新計算 pageHeight。content.scrollTo({top: target, behavior: 'smooth'}) (現代瀏覽器)。img.onload 後重新計算。role="button" tabindex="0" 支持鍵盤操作。| 優點 | 缺點 |
|---|---|
| 零依賴、極輕量 (~1KB) | 無法精準控制段落斷行位置 |
| SEO 友好(內容完整在 DOM 中) | 圖片/表格跨頁可能被切割 |
| 無需後端配合 | 超長內容首屏渲染慢 |
適合:文章詳情、條款展示、合同預覽等靜態長文場景。
不適合:數據列表、需要精確分頁語義的場景(請用後端分頁)。