「標籤貼靠」指在長列表滾動時,當前分類標題 (標籤) 固定於視窗頂部,直到下一分類標題推上來取代。類似 iOS 通訊錄右側字母索引、Edenspiekermann 作品集頁面。核心價值:提供持續的上下文定向,幫助使用者在長列表中快速定位、理解當前所屬分類。
position: sticky (現代首選)<style>
.section-header {
position: sticky;
top: 0;
z-index: 10;
background: white; /* 必須有背景,否則會透出下方內容 */
padding: 0.75rem 1rem;
border-bottom: 1px solid #eee;
font-weight: 600;
/* 可選:陰影增強層疊感 */
box-shadow: 0 2px 4px -2px rgba(0,0,0,.1);
}
</style>
<div class="list">
<div class="section">
<h2 class="section-header">A</h2>
<ul><li>Aaron</li><li>Amy</li>...</ul>
</div>
<div class="section">
<h2 class="section-header">B</h2>
<ul><li>Bob</li><li>Ben</li>...</ul>
</div>
...
</div>
優點:零 JS、效能極佳、瀏覽器原生最佳化、支援巢狀 sticky。
缺點:舊版瀏覽器不支援 (IE 全系列、舊版 Safari 需 -webkit-sticky);無法輕易獲取「當前貼靠的是哪個標籤」以供側邊索引高亮。
const headers = document.querySelectorAll('.section-header');
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
const header = entry.target;
if (entry.boundingClientRect.top <= 0) {
// 標籤即將貼頂 / 正在貼頂
header.classList.add('is-stuck');
// 同步側邊索引高亮
document.querySelectorAll('.index-link').forEach(link => {
link.classList.toggle('active', link.dataset.section === header.dataset.section);
});
} else {
header.classList.remove('is-stuck');
}
});
}, { rootMargin: '0px 0px -100%' }); // 當頂部接觸視窗頂部觸發
headers.forEach(h => observer.observe(h));
getBoundingClientRect (舊專案相容)let currentStuck = null;
window.addEventListener('scroll', throttle(() => {
headers.forEach(header => {
const rect = header.getBoundingClientRect();
if (rect.top <= 0 && rect.bottom > 0) {
// 此標籤正在貼頂
if (currentStuck !== header) {
currentStuck?.classList.remove('is-stuck');
header.classList.add('is-stuck');
currentStuck = header;
updateSideIndex(header.dataset.section);
}
} else if (header === currentStuck && rect.top > 0) {
// 滾回頂部,取消貼靠
header.classList.remove('is-stuck');
currentStuck = null;
updateSideIndex(null);
}
});
}, 16), { passive: true });
scrollIntoView({behavior:'smooth'}) ),同時高亮當前貼靠標籤對應字母。aria-live="polite" 宣告分類變更;鍵盤導航支援 Home/End 跳轉分組。| 問題 | 原因 | 解決 |
|---|---|---|
| sticky 不生效 | 祖先元素有 overflow: hidden/auto/scroll | 移除祖先 overflow 或改用 JS 方案 |
| 標籤貼頂時內容透出 | 缺少背景色 | 給標籤實體背景色或 backdrop-filter: blur() |
| 巢狀 sticky 衝突 | 多層 sticky 顛倒順序 | 內層 top: auto; bottom: 0 或調整 z-index |
| 側邊索引不同步 | IntersectionObserver 觸發時機與視覺貼頂有誤差 | 用 rootMargin: '0px 0px -99.9%' 精確對齊視窗頂部 |
標籤貼靠是長列表導航的「指南針」。優先使用原生 position: sticky,配合 IntersectionObserver 處理側邊索引同步與無障礙宣告,能以最小代碼成本實現專業級體驗。