萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 手工打造懸浮目錄導航菜單(滾動偵測 + 平滑動畫)

功能需求

  • 頁面右側固定懸浮菜單,列出所有章節標題(h1)。
  • 滾動時自動高亮當前閱讀章節。
  • 點擊菜單項平滑滾動至對應章節。
  • 可收合/展開菜單,節省螢幕空間。
  • CSS 動畫實現滑入/滑出,不阻塞主執行緒。

HTML 結構

<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>

CSS:固定定位 + Transform 動畫

.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; }

JavaScript 邏輯

(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();
})();

進階增強

  • IntersectionObserver:替代 scroll 事件,效能更好,自動處理視窗交集判斷。
  • 動態生成菜單:掃描 h1~h3 自動建立巢狀菜單,支援多層級。
  • 響應式:行動裝置改為底部抽屜或漢堡選單。
  • 狀態持久化:localStorage 記住收合狀態。

原始碼歷史對比

原文使用 setTimeout 輪詢定位、document.all 判斷 IE、手動計算 scrollTop、className 切換無過渡動畫。現代寫法採用 position:fixed、transform 動畫、scrollIntoView、IntersectionObserver,程式碼更精簡、效能更佳、無瀏覽器分支。

copyright © 萬盛學電腦網 all rights reserved