如何为有序命名的批量HTML页面添加自动跳转的下一页导航按钮?
使用说明
你只需要将下方的代码批量插入到所有HTML页面的<body>标签内的对应位置即可(想要按钮显示在底部就插入到</body>结束标签之前),无需额外修改其他内容,插入后直接生效。
可用代码(原生JS版,无需引入任何外部依赖)
<!-- 下一页按钮 Start --> <button id="nextPageBtn" style="padding: 8px 16px; background: #2d8cf0; color: #fff; border: none; border-radius: 4px; cursor: pointer; margin: 20px 0;">下一页</button> <script> // 可配置项:如果你知道总页数,直接修改下面的数字即可,比如总共有999页就填999,留空则不做页数上限判断 const maxPage = 999; const nextBtn = document.getElementById('nextPageBtn'); // 获取当前页面文件名 const currentFileName = window.location.pathname.split('/').pop(); // 匹配文件名中的序号 const pageMatch = currentFileName.match(/page(\d+)\.html/i); if (pageMatch) { const currentPageNum = parseInt(pageMatch[1], 10); const nextPageNum = currentPageNum + 1; // 判断是否超过总页数 if (maxPage && nextPageNum > maxPage) { nextBtn.style.display = 'none'; } else { nextBtn.addEventListener('click', () => { window.location.href = `page${nextPageNum}.html`; }); } } else { // 匹配不到文件名规则时隐藏按钮 nextBtn.style.display = 'none'; } </script> <!-- 下一页按钮 End -->
自定义调整说明
- 如果你需要修改按钮文字,直接替换
<button>标签中的「下一页」文字即可 - 如果你需要调整按钮样式,修改
<button>标签中style属性内的CSS规则即可 - 如果你知道书籍总页数,修改
const maxPage = 999一行的数字为实际总页数,到达最后一页时按钮会自动隐藏
jQuery版本(仅当你的页面已经引入jQuery库时使用)
<!-- 下一页按钮 Start --> <button id="nextPageBtn" style="padding: 8px 16px; background: #2d8cf0; color: #fff; border: none; border-radius: 4px; cursor: pointer; margin: 20px 0;">下一页</button> <script> // 可配置项:总页数,填实际数值即可 const maxPage = 999; $(function() { const currentFileName = window.location.pathname.split('/').pop(); const pageMatch = currentFileName.match(/page(\d+)\.html/i); if (!pageMatch) { $('#nextPageBtn').hide(); return; } const currentPageNum = parseInt(pageMatch[1], 10); const nextPageNum = currentPageNum + 1; if (maxPage && nextPageNum > maxPage) { $('#nextPageBtn').hide(); return; } $('#nextPageBtn').on('click', () => { window.location.href = `page${nextPageNum}.html`; }); }); </script> <!-- 下一页按钮 End -->
内容的提问来源于stack exchange,提问作者JackBlack
相关产品推荐
相关产品推荐

