日期 2025 年 11 月 27 日

document.addEventListener('DOMContentLoaded', function () { const perPage = 9; // 每頁顯示幾篇文章 // 先把網址裡 Elementor 的預覽參數拿掉(e-page-xxxx、elementor-preview) (function cleanUrl() { try { const url = new URL(window.location.href); let needClean = false; for (const [key] of url.searchParams) { if (key.indexOf('e-page') === 0 || key.indexOf('elementor-preview') === 0) { needClean = true; break; } } if (needClean) { history.replaceState(null, '', url.pathname + url.hash); } } catch (e) { // ignore } })(); // 1. 找到文章列表容器 let list = null; // 如果你有在 Archive Posts 小工具加 CSS 類別 at99-post-list,先用這個找 const customWidget = document.querySelector('.at99-post-list'); if (customWidget) { // Elementor 小工具內真正裝文章的是 .elementor-posts-container list = customWidget.querySelector('.elementor-posts-container') || customWidget; } // 如果上面沒找到,就直接找預設的 Archive Posts 容器 if (!list) { list = document.querySelector('.elementor-widget-archive-posts .elementor-posts-container') || document.querySelector('.elementor-widget-archive-posts'); } if (!list) { return; // 找不到文章列表就不做事 } // 2. 抓每一篇文章 const items = list.querySelectorAll('article, .elementor-post'); const total = items.length; // 不足一頁就不用顯示分頁 if (total <= perPage) { return; } // 3. 找 / 建立分頁按鈕容器 let pager = document.querySelector('.at99-pagination'); if (!pager) { pager = document.createElement('div'); pager.className = 'at99-pagination'; list.parentNode.insertBefore(pager, list.nextSibling); } const pageCount = Math.ceil(total / perPage); function showPage(page) { const p = Math.max(1, Math.min(page, pageCount)); const start = (p - 1) * perPage; const end = start + perPage; items.forEach((item, i) => { item.style.display = (i >= start && i < end) ? '' : 'none'; }); pager.querySelectorAll('button').forEach(btn => { btn.classList.toggle('is-active', Number(btn.dataset.page) === p); }); // 再保險一次:切頁時永遠把網址鎖在原本路徑(不帶任何參數) try { const url = new URL(window.location.href); history.replaceState(null, '', url.pathname + url.hash); } catch (e) { // ignore } } // 4. 建立 1 2 3 ... 的分頁按鈕 pager.innerHTML = ''; // 清空舊的內容 for (let i = 1; i <= pageCount; i++) { const btn = document.createElement('button'); btn.type = 'button'; btn.dataset.page = i; btn.textContent = i; btn.addEventListener('click', function () { showPage(Number(this.dataset.page)); }); pager.appendChild(btn); } // 顯示第一頁 showPage(1); });