概览
抽屉式导航栏是一个面板,它会从视口边缘滑入,覆盖在页面内容之上,并使背后的所有内容变暗。它通过触发按钮打开,并通过将面板滑出屏幕、点按变暗的背景或按 Escape 键来关闭。
本指南将抽屉式导航栏实现为:
popover="manual"元素会提升到顶层,因此无论堆叠上下文如何,该面板及其::backdrop都会叠加在页面上的所有其他元素之上。- 一个具有两个 CSS 滚动贴靠停止点的水平滚动容器(一个用于“打开”,一个用于“关闭”),因此滑动滑动手势由浏览器原生处理。这样,您无需编写 JavaScript 指针事件代码,即可免费获得动量、速度和中断跟踪功能。
- 一种滚动驱动的动画,可将背景幕的不透明度与滚动位置相关联,以便在用户拖动面板时,调暗效果能够平滑地淡入和淡出。
- 面板上的
IntersectionObserver,用于检测面板何时完全进入或完全离开视口,并利用这些时刻更新焦点、aria-expanded和inert。
这种方法优于 JavaScript 驱动的 transform 动画,因为滚动机制让用户可以直接控制面板的位置(由用户的手指驱动,而不是补间动画),并且更贴近用户在原生移动应用中习惯的互动模式。
实现
1. Markup
抽屉式导航栏是一个包含水平滚动条的弹出式窗口,其中包含可见的“工作表”。触发按钮位于页面内容中。
<!-- 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 使整个页面变暗,并且滑动界面从一侧边缘延伸到另一侧边缘。默认的用户代理 popover 样式(居中、自动调整大小、带边框)会造成干扰,必须重置。
.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 实现关闭,因此它不依赖于 popover API 的定义行为,即轻度关闭、popovertarget 属性、顶层管理的 Escape 处理或焦点管理。它实际使用的唯一弹出式窗口功能是顶层提升(通过 showPopover())和 ::backdrop 伪元素。
如果需要更广泛的浏览器支持,请勿根据功能检测结果进行分支,而应完全不使用 popover。删除 popover="manual" 属性,将顶层提升替换为 position: fixed 和高 z-index,将 ::backdrop 替换为样式相同的同级元素(使用相同的 --drawer-backdrop 自定义属性),并从类(而非 showPopover()/hidePopover())切换可见性。组件的其余部分(滚动贴靠、滚动驱动的背景动画、IntersectionObserver 和关闭处理程序)保持不变。