h1)。<div id="content">
<h1 id="ch1">Chapter 1</h1> <p>...</p>
<h1 id="ch2">Chapter 2</h1> <p>...</p>
<h1 id="ch3">Chapter 3</h1> <p>...</p>
<h1 id="ch4">Chapter 4</h1> <p>...</p>
</div>
<nav class="float-menu" id="floatMenu">
<button class="toggle-btn" aria-label="切換菜單" aria-expanded="false">隱藏</button>
<ul class="menu-list">
<li><a href="#ch1">Chapter 1</a></li>
<li><a href="#ch2">Chapter 2</a></li>
<li><a href="#ch3">Chapter 3</a></li>
<li><a href="#ch4">Chapter 4</a></li>
</ul>
</nav>
.float-menu {
position: fixed; top: 20%; right: 0; z-index: 1000;
width: 200px; background: #fff; border: 1px solid #ddd;
border-radius: 8px 0 0 8px; box-shadow: -2px 0 8px rgba(0,0,0,.1);
transition: transform 0.4s ease;
}
.float-menu.collapsed { transform: translateX(calc(100% - 40px)); } /* 僅露出切換鈕 */
.float-menu .toggle-btn {
position: absolute; left: -40px; top: 50%; transform: translateY(-50%);
width: 40px; height: 80px; background: #fff; border: 1px solid #ddd;
border-right: none; border-radius: 8px 0 0 8px; cursor: pointer;
}
.menu-list { list-style: none; padding: 0; margin: 0; }
.menu-list a { display: block; padding: 10px 16px; color: #333; text-decoration: none; border-bottom: 1px solid #eee; }
.menu-list a.active { color: #007aff; font-weight: bold; }
(function() {
const menu = document.getElementById('floatMenu');
const toggleBtn = menu.querySelector('.toggle-btn');
const links = menu.querySelectorAll('.menu-list a');
const headings = document.querySelectorAll('#content h1');
const headingTops = Array.from(headings).map(h => h.offsetTop);
let current = -1;
// 1. 滾動偵測高亮
function onScroll() {
const scrollY = window.scrollY || document.documentElement.scrollTop;
let idx = headingTops.findLastIndex(top => top <= scrollY + 100); // 100px 緩衝
if (idx === -1) idx = 0;
if (idx !== current) {
links.forEach(l => l.classList.remove('active'));
links[idx].classList.add('active');
current = idx;
}
}
window.addEventListener('scroll', onScroll, { passive: true });
// 2. 平滑滾動(原生 CSS scroll-behavior 亦可)
menu.querySelector('.menu-list').addEventListener('click', e => {
const a = e.target.closest('a');
if (!a) return;
e.preventDefault();
const target = document.querySelector(a.getAttribute('href'));
if (target) target.scrollIntoView({ behavior: 'smooth', block: 'start' });
// 手動更新高亮(scroll 事件會再觸發,這裡可選)
const idx = Array.from(links).indexOf(a);
if (idx !== -1) { links.forEach(l => l.classList.remove('active')); a.classList.add('active'); current = idx; }
});
// 3. 收合/展開切換
toggleBtn.addEventListener('click', () => {
const collapsed = menu.classList.toggle('collapsed');
toggleBtn.textContent = collapsed ? '顯示' : '隱藏';
toggleBtn.setAttribute('aria-expanded', !collapsed);
});
// 初始化
onScroll();
})();
h1~h3 自動建立巢狀菜單,支援多層級。localStorage 記住收合狀態。原文使用 setTimeout 輪詢定位、document.all 判斷 IE、手動計算 scrollTop、className 切換無過渡動畫。現代寫法採用 position:fixed、transform 動畫、scrollIntoView、IntersectionObserver,程式碼更精簡、效能更佳、無瀏覽器分支。