總覽
導覽匣是從可視區域邊緣滑入頁面內容上方的面板,會使後方的所有內容變暗。使用者可透過觸發按鈕開啟側邊面板,並透過以下方式關閉:將面板滑出畫面、輕觸變暗的背景,或按下 Escape 鍵。
本指南實作的導覽匣如下:
popover="manual"元素會升級至頂層,因此面板和::backdrop會疊加在頁面上的所有其他元素上,無論堆疊內容為何。- 水平捲動容器,具有兩個 CSS 捲動貼齊停止點,一個用於「開啟」,另一個用於「關閉」,因此滑動手勢會由瀏覽器原生處理。這項功能可免費追蹤動量、速度和中斷情形,不需使用 JavaScript 指標事件程式碼。
- 捲動驅動動畫,將背景的不透明度與捲動位置連結,因此當使用者拖曳面板時,調暗效果會流暢地淡入和淡出。
- 面板上的
IntersectionObserver,可偵測面板何時完全進入或完全離開可視區域,並利用這些時刻更新焦點、aria-expanded和inert。
這種做法比 JavaScript 驅動的 transform 動畫更理想,因為捲動機制可讓使用者直接控制面板的位置 (由手指驅動,而非補間動畫),而且更符合使用者在原生行動應用程式中習慣的互動模式。
導入作業
1. 標記
導覽匣是單一彈出式視窗,內含水平捲動器,其中包含可見的「工作表」。觸發按鈕位於網頁內容中。
<!-- popover="manual" is REQUIRED. Do not use popover="auto" or "hint". -->
<div class="Drawer" id="drawer" popover="manual">
<div class="Drawer-scroller">
<nav class="Drawer-sheet" tabindex="-1">
<!-- tabindex="-1" makes the sheet programmatically focusable so we
can move focus into it when the drawer opens, without adding it
to the natural tab order. -->
<ul>
<li><a href="/page-1">Page 1</a></li>
<li><a href="/page-2">Page 2</a></li>
<!-- ... -->
</ul>
</nav>
</div>
</div>
<main>
<header>
<!-- aria-controls links the trigger to the drawer; aria-expanded
reflects the current state for assistive tech. -->
<button id="drawer-open"
aria-label="Menu"
aria-expanded="false"
aria-controls="drawer">
<!-- MANDATORY: Inline decorative SVGs MUST define aria-hidden="true" -->
<svg aria-hidden="true" viewBox="0 0 24 24">...</svg>
</button>
</header>
<!-- Page content. -->
</main>
2. 樣式
重設彈出式視窗並填滿可視區域
彈出式視窗必須覆蓋整個可視區域,因此 ::backdrop 會調暗整個頁面,且滑動介面會延伸至邊緣。預設的使用者代理程式彈出式視窗樣式 (置中、自動調整大小、有邊框) 會造成干擾,因此必須重設。
.Drawer {
/* min() caps the sheet width on large screens but on a phone leaves
a 20% peek of page content visible, which is the affordance that
tells the user they can tap outside to dismiss. */
--drawer-width: min(20em, 80dvw);
/* Custom property driven by the scroll-driven animation below.
0 = drawer fully closed (transparent backdrop).
1 = drawer fully open (visible backdrop). */
--drawer-backdrop: 0;
/* Reset UA popover style that would constrain the element. */
width: auto;
height: auto;
background: transparent;
border: 0;
overflow: visible;
}
/* Style the popover's ::backdrop to achieve the overlay effect and
provide visual affordances indicating that the rest of the page is inert */
.Drawer::backdrop {
background: #000;
/* Use calc() to limit the opacity range so the content beneath is visible */
opacity: calc(var(--drawer-backdrop) / 2);
}
使用捲動貼齊功能建構滑動介面
捲動器是寬度大於可視區域的水平格線:第 1 欄包含工作表 (寬度 --drawer-width),第 2 欄是空白的虛擬元素間隔,寬度與可視區域相同。在兩個資料欄之間貼齊,即可開啟和關閉導覽匣。
.Drawer-scroller {
position: relative;
display: grid;
/* Sheet on the left, full-viewport spacer on the right. The user
scrolls between the two snap stops to open and close. */
grid-template-columns: var(--drawer-width) 100%;
overflow-x: scroll;
/* Stop the swipe from chaining into the page's vertical scroll
when the user reaches either snap edge. */
overscroll-behavior: none;
scrollbar-width: none;
/* `mandatory` guarantees the drawer always settles fully open or
fully closed — never half-open after a partial swipe. */
scroll-snap-type: x mandatory;
}
/* Enable smooth scrolling natively, but only if the user has not
requested reduced motion. */
@media (prefers-reduced-motion: no-preference) {
.Drawer-scroller {
scroll-behavior: smooth;
}
}
/* The empty spacer that creates the "closed" snap stop. */
.Drawer-scroller::after {
content: '';
scroll-snap-align: end;
/* Open the popover already scrolled to this stop (drawer off-screen),
so the JS only needs to scroll to the open position to
animate it in. */
scroll-initial-target: nearest;
}
.Drawer-sheet {
display: grid;
grid-template-rows: auto 1fr;
/* Use `svh` (small viewport height) — not `vh` or `dvh` — so the
sheet height does not jump when the iOS Safari address bar
resizes mid-swipe. */
height: 100svh;
background: #333;
color: #fff;
overflow-y: auto;
scroll-snap-align: start;
scrollbar-width: none;
}
將背景不透明度與捲動位置連結
捲動驅動動畫會將 --drawer-backdrop 從 1 (開啟) 對應至 0 (關閉),涵蓋捲動器的範圍,因此背景會完美同步淡入和淡出。
/* MANDATORY: Wrap this entire block in @supports. Browsers that don't
support animation-timeline still parse the @keyframes and would
apply the animation's `0%` value (--drawer-backdrop: 1) at all
times, leaving the backdrop permanently opaque. The @supports gate
ensures the animation is only registered where it actually works. */
@supports (animation-timeline: scroll()) {
.Drawer {
/* timeline-scope lets .Drawer reference a scroll-timeline that
is defined on its descendant (the scroller). Without this, the
timeline name is not visible to the .Drawer element. */
timeline-scope: --drawer-fade;
animation: fade-drawer-backdrop linear both;
animation-timeline: --drawer-fade;
}
.Drawer-scroller {
/* The horizontal scroll position of this element drives the
timeline named `--drawer-fade`. */
scroll-timeline: --drawer-fade x;
}
/* @property is REQUIRED. Without registering --drawer-backdrop with
a `<number>` syntax, the browser treats it as a string and cannot
interpolate it — the backdrop would jump from 0 to 1 with no
fade. */
@property --drawer-backdrop {
syntax: '<number>';
inherits: true;
initial-value: 0;
}
@keyframes fade-drawer-backdrop {
/* Scroll position 0 = drawer fully open = backdrop visible. */
0% { --drawer-backdrop: 1 }
/* Scroll position 100% = drawer fully closed = backdrop hidden. */
100% { --drawer-backdrop: 0 }
}
}
3. 開啟和關閉導覽匣
開啟分為兩個步驟:將彈出式視窗升級至頂層,然後捲動工作表至檢視畫面。關閉時只需一個步驟:捲動回空白元素,觀察器 (步驟 4) 會在工作表完全移出畫面後隱藏彈出式視窗。
const drawer = document.getElementById('drawer');
const openBtn = document.getElementById('drawer-open');
const scroller = drawer.querySelector('.Drawer-scroller');
const sheet = drawer.querySelector('.Drawer-sheet');
function openDrawer() {
// Show the popover first so the element is in the top layer before
// we trigger any scrolling. `scroll-initial-target` (set on the
// ::after spacer) places the initial scroll position at the closed
// stop, so the drawer enters the top layer already off-screen.
drawer.showPopover();
// Scroll the sheet into view. The `behavior: 'auto'` option defers
// to the CSS `scroll-behavior` property, which will be smooth unless
// the user prefers reduced motion. Snap takes over at the end and
// locks the drawer fully open.
scroller.scrollTo({left: 0, behavior: 'auto'});
}
function closeDrawer() {
// Scroll back to the spacer. Do NOT call hidePopover() here —
// doing so would remove the element from the top layer mid-animation
// and the close animation would not be visible. The
// IntersectionObserver in step 4 hides the popover once the sheet
// has actually left the viewport.
scroller.scrollTo({left: scroller.offsetWidth, behavior: 'auto'});
}
4. 偵測開啟和關閉狀態
請使用工作表上的 IntersectionObserver (而非捲動位置) 做為導覽匣狀態的可靠資料來源。無論工作表如何移動 (使用者滑動、程式輔助捲動、貼齊定位),觀察器都會觸發,因此所有關閉路徑都會匯聚在同一個回呼中。
function onDrawerOpened() {
// Mark the rest of the page inert so keyboard and screen-reader
// users cannot tab into content hidden behind the drawer.
document.querySelector('main').inert = true;
openBtn.setAttribute('aria-expanded', 'true');
// Move focus into the drawer for keyboard users.
sheet.focus();
}
function onDrawerClosed() {
// Hide the popover only after the close animation completes,
// so the slide-out is visible to the user.
drawer.hidePopover();
document.querySelector('main').inert = false;
openBtn.setAttribute('aria-expanded', 'false');
}
// Treat "any pixel of the sheet visible inside the popover root" as
// "open enough to count as not closed". This threshold is intentionally
// tiny so the closed callback only fires once the sheet is truly gone.
const visibleThreshold = 1 / window.innerWidth;
const observer = new IntersectionObserver(
(entries) => {
// During programmatic scrolling the observer can deliver multiple
// entries in one batch. Only the most recent describes the
// current state; earlier entries are intermediate positions.
const entry = entries.at(-1);
if (entry.intersectionRatio < visibleThreshold) onDrawerClosed();
if (entry.intersectionRatio === 1) onDrawerOpened();
},
// root: drawer makes the popover element the intersection root,
// so the ratio reflects the sheet's visibility within the popover
// (i.e. how much of it has been swiped on-screen).
{root: drawer, threshold: [visibleThreshold, 1]},
);
observer.observe(sheet);
5. 連結觸發條件和關閉處理常式
// Open trigger.
openBtn.addEventListener('click', openDrawer);
// Light-dismiss: a tap on the dimmed area (anywhere inside the
// popover but outside the sheet) closes the drawer. We implement
// this manually because popover="manual" disables the browser's
// built-in light-dismiss (which would also fire mid-swipe — see step 1).
drawer.addEventListener('click', (event) => {
if (!sheet.contains(event.target)) closeDrawer();
});
// Escape key. Listen on document because focus may be inside the
// drawer when the user presses Escape.
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape') closeDrawer();
});
備用策略
Popover API、淡出背景的捲動驅動動畫和 scroll-initial-target 都是漸進增強功能,具有簡單的備用方案,如果需要廣泛的瀏覽器支援,可以輕鬆實作。
背景淡出備用 (不支援 animation-timeline):
使用 CSS.supports('animation-timeline: scroll()') 偵測,如果系統不支援,則從 scroll 事件監聽器寫入 --drawer-backdrop。步驟 2 的 CSS @supports 區塊可確保不支援的瀏覽器不會套用主要畫面格,因此 JavaScript 值是唯一的寫入器。
if (!CSS.supports('animation-timeline: scroll()')) {
scroller.addEventListener('scroll', () => {
// Same mapping as the @keyframes: 0 scroll = 1 (open),
// sheet-width scroll = 0 (closed).
const ratio = 1 - scroller.scrollLeft / sheet.offsetWidth;
drawer.style.setProperty('--drawer-backdrop', ratio);
});
}
初始捲動位置備用方案 (不支援 scroll-initial-target):
使用 CSS.supports('scroll-initial-target', 'nearest') 偵測,並在 openDrawer() 內,於 showPopover() 後立即將捲動器跳轉至關閉位置。如果沒有這個屬性,導覽匣會立即顯示在開啟位置,不會有滑入動畫。
async function openDrawer() {
drawer.showPopover();
if (!CSS.supports('scroll-initial-target', 'nearest')) {
// Jump-scroll to the closed stop so the scroll below
// animates the drawer in from off-screen.
scroller.scrollTo({left: scroller.offsetWidth, behavior: 'instant'});
// Wait two animation frames for the jump-scroll to commit.
// A single rAF is not enough — the second `scrollTo` would
// cancel the first before the browser has a chance to apply it.
await new Promise((r) =>
requestAnimationFrame(() => requestAnimationFrame(r))
);
}
scroller.scrollTo({left: 0, behavior: 'auto'});
}
@property 備用 (未註冊自訂屬性):
@property 僅在捲動驅動動畫在主要畫面格之間插補 --drawer-backdrop 時才需要,如果未註冊,屬性會視為字串,並在 0 和 1 之間跳動,不會淡出。如果上述捲動驅動動畫備用方案已就緒,JavaScript 會在每個捲動影格中將新的數字字串寫入 --drawer-backdrop,且不會插補,因此不需要個別的 @property 備用方案,因為所有支援捲動驅動動畫的瀏覽器也支援 @property。
Popover API 備用方案 (不支援 popover 屬性):
由於這個元件使用 popover="manual",且完全透過 JavaScript 實作關閉功能,因此不依賴彈出式視窗 API 的定義行為,例如輕觸關閉、popovertarget 屬性、頂層管理的 Escape 處理或焦點管理。它實際使用的彈出式視窗功能只有頂層宣傳 (透過 showPopover()) 和 ::backdrop 虛擬元素。
如果需要更廣泛的瀏覽器支援,請勿根據功能偵測結果分支,直接不使用彈出式視窗即可。捨棄 popover="manual" 屬性,將頂層宣傳活動替換為 position: fixed 和高 z-index,將 ::backdrop 替換為樣式相同的同層元素 (使用相同的 --drawer-backdrop 自訂屬性),並從類別切換顯示設定,而非 showPopover()/hidePopover()。其餘元件 (捲動貼齊、捲動驅動的背景動畫、IntersectionObserver 和關閉處理常式) 則維持不變。