滑動導航菜單是移動端、觸屏設備常見交互模式。原代碼使用 setInterval 輪詢、手動計算寬度、document.write 動態創建 DOM、IE 專有 document.all、全局變量污染等遠古模式。本文提供三種現代實現:CSS Scroll Snap (零 JS)、IntersectionObserver + CSS 變量 (指示器同步)、Web Component 封裝 (框架無關),實現高性能、無障礙、響應式、可主題化的滑動導航。
現代瀏覽器完整支持 CSS Scroll Snap,無需任何 JS 即可實現原生級滑動體驗:
<nav class="scroll-nav" role="navigation" aria-label="產品分類">
<ul class="scroll-nav-list">
<li><a href="#phones" class="scroll-nav-item"><img src="phone.svg" alt=""><span>手機</span></a></li>
<li><a href="#laptops" class="scroll-nav-item"><img src="laptop.svg" alt=""><span>筆電</span></a></li>
<li><a href="#tablets" class="scroll-nav-item"><img src="tablet.svg" alt=""><span>平板</span></a></li>
<li><a href="#watches" class="scroll-nav-item"><img src="watch.svg" alt=""><span>手錶</span></a></li>
<li><a href="#audio" class="scroll-nav-item"><img src="audio.svg" alt=""><span>音頻</span></a></li>
<li><a href="#accessories" class="scroll-nav-item"><img src="accessory.svg" alt=""><span>配件</span></a></li>
</ul>
</nav>
<style>
.scroll-nav {
--item-min-width: 80px;
--gap: 12px;
--padding: 16px;
overflow-x: auto;
overscroll-behavior-x: contain;
scroll-snap-type: x mandatory;
-webkit-overflow-scrolling: touch; /* iOS 惯性滾動 */
scrollbar-width: none; /* Firefox 隱藏滾動條 */
background: var(--nav-bg, #fff);
border-bottom: 1px solid var(--border, #eee);
}
.scroll-nav::-webkit-scrollbar { display: none; } /* Chrome/Safari 隱藏滾動條 */
.scroll-nav-list {
display: flex;
gap: var(--gap);
padding: var(--padding);
margin: 0;
list-style: none;
min-height: 48px;
}
.scroll-nav-item {
flex: 0 0 auto;
min-width: var(--item-min-width);
scroll-snap-align: start; /* 關鍵:吸附對齊 */
display: flex;
flex-direction: column;
align-items: center;
gap: 6px;
padding: 8px 12px;
color: var(--text, #333);
text-decoration: none;
font-size: 13px;
font-weight: 500;
border-radius: 8px;
transition: color 0.2s, background 0.2s;
white-space: nowrap;
}
.scroll-nav-item img { width: 28px; height: 28px; }
.scroll-nav-item:hover, .scroll-nav-item:focus-visible {
color: var(--primary, #007bff);
background: var(--hover-bg, #f0f7ff);
outline: none;
}
.scroll-nav-item:focus-visible {
box-shadow: 0 0 0 2px var(--primary, #007bff);
}
/* 滾動指示器 (純 CSS) */
.scroll-nav::after {
content: '';
position: sticky;
left: 0;
bottom: 0;
height: 3px;
background: linear-gradient(90deg, transparent 50%, var(--primary, #007bff) 50%);
background-size: 200% 100%;
animation: scrollIndicator 20s linear infinite;
pointer-events: none;
}
@keyframes scrollIndicator {
to { background-position: -200% 0; }
}
/* 深色模式 */
@media (prefers-color-scheme: dark) {
.scroll-nav { --nav-bg: #1c1c1e; --border: #38383a; --text: #f5f5f7; --hover-bg: #2c2c2e; }
}
當導航項對應頁面區塊時,滾動頁面自動高亮對應導航項:
<nav class="scroll-nav" id="mainNav">
<ul class="scroll-nav-list">
<li><a href="#section1" class="scroll-nav-item" data-target="section1">概覽</a></li>
<li><a href="#section2" class="scroll-nav-item" data-target="section2">特性</a></li>
<li><a href="#section3" class="scroll-nav-item" data-target="section3">定價</a></li>
<li><a href="#section4" class="scroll-nav-item" data-target="section4">評價</a></li>
</ul>
<div class="scroll-nav-indicator" aria-hidden="true"></div>
</nav>
<main>
<section id="section1">...</section>
<section id="section2">...</section>
<section id="section3">...</section>
<section id="section4">...</section>
</main>
<style>
.scroll-nav { position: sticky; top: 0; z-index: 100; /* 繼承方案一樣式 */ }
.scroll-nav-indicator {
position: absolute;
bottom: 0; left: 0;
height: 3px;
background: var(--primary, #007bff);
border-radius: 0 0 8px 8px;
transition: transform 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94), width 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
will-change: transform, width;
}
<script>
class ScrollNavIndicator {
constructor(navSelector) {
this.nav = document.querySelector(navSelector);
this.list = this.nav.querySelector('.scroll-nav-list');
this.indicator = this.nav.querySelector('.scroll-nav-indicator');
this.items = Array.from(this.nav.querySelectorAll('.scroll-nav-item'));
this.sections = this.items.map(item => document.getElementById(item.dataset.target)).filter(Boolean);
this.init();
}
init() {
// 點擊平滑滾動
this.items.forEach(item => {
item.addEventListener('click', e => {
e.preventDefault();
const target = document.getElementById(item.dataset.target);
target?.scrollIntoView({ behavior: 'smooth', block: 'start' });
});
});
// IntersectionObserver 監測區塊可見度
this.observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const index = this.sections.indexOf(entry.target);
if (index >= 0) this.updateIndicator(index);
}
});
}, {
rootMargin: '-20% 0px -70% 0px', // 觸發區域:視口中部 50%
threshold: [0, 0.5, 1]
});
this.sections.forEach(section => this.observer.observe(section));
// 初始定位
this.updateIndicator(0);
}
updateIndicator(index) {
const item = this.items[index];
if (!item) return;
const rect = item.getBoundingClientRect();
const listRect = this.list.getBoundingClientRect();
this.indicator.style.transform = `translateX(${rect.left - listRect.left}px)`;
this.indicator.style.width = `${rect.width}px`;
// 更新 ARIA
this.items.forEach((el, i) => el.setAttribute('aria-current', i === index ? 'location' : 'false'));
}
destroy() {
this.observer.disconnect();
}
}
// 初始化
document.addEventListener('DOMContentLoaded', () => {
window.scrollNav = new ScrollNavIndicator('#mainNav');
});
<scroll-nav multiple data-align="center">
<scroll-nav-item href="#home" icon="🏠">首頁</scroll-nav-item>
<scroll-nav-item href="#products" icon="📦">產品</scroll-nav-item>
<scroll-nav-item href="#about" icon="ℹ️">關於</scroll-nav-item>
<scroll-nav-item href="#contact" icon="✉️">聯繫</scroll-nav-item>
</scroll-nav>
<script>
class ScrollNav extends HTMLElement {
static get observedAttributes() { return ['multiple', 'align']; }
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `
`;
this.nav = this.shadowRoot.querySelector('.nav');
this.list = this.shadowRoot.querySelector('.list');
}
connectedCallback() {
this.observeItems();
}
observeItems() {
// 監聽 slot 內容變化
const slot = this.shadowRoot.querySelector('slot');
slot?.addEventListener('slotchange', () => this.updateItems());
this.updateItems();
}
updateItems() {
this.items = Array.from(this.querySelectorAll('scroll-nav-item'));
this.items.forEach((item, i) => {
item.setAttribute('role', 'tab');
item.setAttribute('aria-selected', 'false');
item.tabIndex = 0;
});
if (this.items[0]) this.items[0].setAttribute('aria-selected', 'true');
}
attributeChangedCallback(name, oldVal, newVal) {
if (name === 'align') {
this.list.style.setProperty('--snap-align', newVal);
this.items.forEach(item => item.style.scrollSnapAlign = newVal);
}
}
}
class ScrollNavItem extends HTMLElement {
static get observedAttributes() { return ['href', 'icon', 'disabled']; }
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.render();
}
connectedCallback() {
this.shadowRoot.querySelector('a')?.addEventListener('click', e => this.onClick(e));
this.addEventListener('keydown', e => this.onKeydown(e));
}
render() {
const href = this.getAttribute('href') || '#';
const icon = this.getAttribute('icon') || '';
const label = this.textContent.trim();
const disabled = this.hasAttribute('disabled');
this.shadowRoot.innerHTML = `
${label}
`;
}
onClick(e) {
if (this.hasAttribute('disabled')) e.preventDefault();
// 通知父組件
this.dispatchEvent(new CustomEvent('nav-select', { detail: { href: this.getAttribute('href') }, bubbles: true, composed: true }));
}
onKeydown(e) {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
this.shadowRoot.querySelector('a')?.click();
}
}
}
customElements.define('scroll-nav', ScrollNav);
customElements.define('scroll-nav-item', ScrollNavItem);
| 指標 | 原版 (setInterval + 手動計算) | CSS Scroll Snap | IntersectionObserver | Web Component |
|---|---|---|---|---|
| 主線程阻塞 | 高 (定時器輪詢) | 零 (瀏覽器原生) | 極低 (異步回調) | 極低 |
| 滑動流暢度 | 卡頓、不跟手 | 原生 60fps/120fps | 原生滾動 + 指示器動畫 | 原生滾動 |
| 代碼體積 | ~2KB (壓縮後) | ~300B CSS | ~1KB JS + CSS | ~2KB (含模板) |
| 無障礙 | 無 | 語義化 HTML 基礎 | 完整 ARIA + 鍵盤 | 完整 ARIA + 鍵盤 + Shadow DOM 隔離 |
| 響應式 | 硬編碼寬度 | CSS 變量 + 媒體查詢 | CSS 變量 | 屬性驅動 + CSS 變量 |
| 框架集成 | 困難 (全局污染) | Class 名隔離 | Class 名隔離 | 原生元素,完美集成 |
滑動導航菜單的現代化演進路徑:手動計算定時器 → CSS Scroll Snap 原生吸附 → IntersectionObserver 語義同步 → Web Component 標準化封裝。建議:純展示型導航用方案一 (零 JS)、單頁錨點導航用方案二、設計系統組件庫用方案三。核心原則:盡可能下沉到瀏覽器原生能力 (CSS/HTML)、JS 僅處理邏輯協調、組件化封裝實現跨框架複用。