堆栈展开细目

概览

堆叠式下钻是一种分层导航模式,在移动应用中很常见,其中激活链接会将新的全屏视图推送到上一个视图之上。视图的内容由应用定义,例如设置子页面、信息流中的会话、文件浏览器中的文件夹、图库中的详情页面等。用户可以通过将当前视图向右滑动到屏幕外或点按返回按钮来返回。浏览器历史记录会保持同步,因此操作系统级返回手势、深层链接和前进/返回导航都能顺畅运行。

本指南将该堆栈实现为:

  • 一个水平 CSS 滚动贴靠容器,其中每个视图都恰好是一个贴靠停止点。向下钻取会附加一个新视图并平滑滚动到该视图;向后滑动的手势由浏览器原生处理,无需使用指针事件 JavaScript 即可免费提供动量、速度和中断跟踪。
  • 堆栈上的 scrollsnapchange 事件监听器,在贴靠目标发生变化时触发。这用作“活动视图已更改”的单一事实来源,因此滑动、点击、程序化滚动和 popstate 路径都会汇聚到一个回调中,该回调会更新 inert、恢复焦点、修剪用户滑过的视图,并协调浏览器历史记录。
  • pushState / popstate 集成,以便每次深入探索都会添加一个历史记录条目,操作系统级返回手势可正常运行,并且深层链接可直接打开正确的视图。
  • 每个视图上都有一个(可选)滚动驱动的 view() 动画,可产生与滑动操作直接相关的视差 + 变暗 + 阴影效果,因此可见动作是由用户的手指驱动,而不是补间动画。

这种方法优于 JavaScript 驱动的 transform 动画,因为贴靠机制让用户可以通过手势直接控制面板的位置(由用户的手指驱动,而不是补间动画),并且符合用户对原生移动应用的预期交互模式。

实现

1. Markup

静态 HTML 只是一个空堆栈容器;视图是在 JavaScript 中构建的,并在用户导航时附加。

<div class="Stack">
  <!-- Intentionally empty. The initial view is appended by JavaScript
       at init time (step 8). -->
</div>

每个视图都是 .Stack(贴靠目标)的 .Stack-view 直接子级,其中包含一个 .Stack-viewContent 封装容器(视图内容所在的位置,也是视差转换应用的位置 - 请参阅第 2 步)。在任何时刻,堆栈中每个活跃的历史记录条目都有一个视图,从左到右按深入分析顺序排列。在用户从根节点向下钻取两个级别后,呈现的 DOM 如下所示:

<div class="Stack">
  <!-- Root view. Has whatever content makes sense as the entry point
       of this section of the app. No back button — there is nothing
       behind the root in the stack. -->
  <div class="Stack-view" inert>
    <div class="Stack-viewContent">
      <!-- Root content; includes <a href> links that drill in. -->
    </div>
  </div>

  <!-- First-level drill-down view. The user got here by activating a
       link in the root view. -->
  <div class="Stack-view" inert>
    <div class="Stack-viewContent">
      <header>
        <!-- DO include a back button. The swipe gesture only works on
             touch — keyboard and pointer users need an explicit control. -->
        <button class="back" aria-label="Back"></button>
        <!-- Title / breadcrumb / etc. -->
      </header>
      <main>
        <!-- View content; may include further drill-down <a href> links. -->
      </main>
    </div>
  </div>

  <!-- Second-level drill-down view. Currently visible — no `inert`
       attribute. Same shape as the first-level view. -->
  <div class="Stack-view">
    <div class="Stack-viewContent">
      <header>
        <button class="back" aria-label="Back"></button>
        <!-- ... -->
      </header>
      <main><!-- ... --></main>
    </div>
  </div>
</div>

注意:

  • 除当前可见的视图外,所有视图都带有 inert 属性。此属性由第 7 步中的 scrollsnapchange 处理程序自动应用/移除,请勿通过视图构建器设置此属性。
  • 用户通过滑动返回操作越过的视图会从 DOM 中移除(同样通过第 7 步),因此堆栈中的子级数量永远不会超过 currentDepth + 1 个。如果向前导航返回到这些页面,系统会根据其缓存的网址路径按需重新构建这些页面。

2. 样式

堆叠滚动条

该堆栈是一个水平网格,其中每个子视图的宽度都与容器完全相同,并通过 CSS 滚动贴靠强制执行“每次贴靠一个视图”。这正是滑动返回手势具有原生感的原因。

.Stack {
  /* Use dvh so the height tracks the dynamic viewport on mobile, where
     the address bar can show/hide. svh would clip during the address bar
     animation; vh leaks under it. */
  height: 100dvh;

  /* Lay views out left-to-right, each one full-width, so horizontal
     scrolling moves between them one at a time. */
  display: grid;
  grid-auto-flow: column;
  grid-auto-columns: 100%;
  grid-template-rows: 100%;
  overflow-x: auto;

  /* `mandatory` guarantees the stack always settles fully on a view —
     never half-way between two. */
  scroll-snap-type: x mandatory;
  /* Prevent the swipe-back gesture from chaining into the browser's
     own history-back gesture (iOS, some Android) or the page's vertical
     scroll. The user is navigating the stack, not the page. */
  overscroll-behavior-x: none;
}

/* Hide the visual scrollbar — the snap and the parallax are the
   affordances; a horizontal scrollbar would look out of place. */
.Stack::-webkit-scrollbar {
  display: none;
}

/* MANDATORY: Opt into smooth programmatic scrolling via CSS, gated on
   prefers-reduced-motion. JS code calls scrollTo/scrollBy with
   behavior: 'auto' which defers to this rule, so the OS-level reduced-
   motion preference automatically downgrades to instant scrolling
   without any per-call JS branching. */
@media (prefers-reduced-motion: no-preference) {
  .Stack {
    scroll-behavior: smooth;
  }
}

.Stack-view {
  scroll-snap-align: start;
  /* `always` prevents the user from blowing through more than one view
     per gesture, so depth changes always happen one step at a time. */
  scroll-snap-stop: always;
}

/* MANDATORY: A separate inner element is required for the parallax
   transform below. Applying transforms directly to the snap target
   (.Stack-view) would feed back into the scroll container's snap
   geometry and the scroller would jump mid-gesture. */
.Stack-viewContent {
  width: 100%;
  height: 100%;
  background-color: #fff;
  /* Each view scrolls its own content vertically, independent of the
     stack's horizontal scroll. */
  overflow-y: auto;
}

“堆叠”效果(视差/变暗/阴影)

滚动驱动的 view(inline) 动画会跟踪每个视图在堆叠滚动条中的进度,并对退出视图应用视差 + 变暗效果,同时对进入的下钻视图应用阴影,使其看起来像是堆叠在上一个视图上的“卡片”。

/* MANDATORY: Wrap the animation block in @supports. Browsers without
   scroll-driven animations still parse the @keyframes and would
   apply the `to` state as a static style, leaving every view
   permanently transformed. The @supports gate confines the animation
   to browsers where it actually animates. */
@supports (animation-timeline: view()) {
  .Stack-viewContent {
    /* view(inline) tracks this element's progress through its nearest
       scrollable ancestor on the inline (x) axis. */
    animation: parallax linear both;
    animation-timeline: view(inline);
    /* Only animate the EXIT phase — when this view is being covered
       by a deeper one. During its own entry the view stays at rest,
       so the fresh content is fully bright and in position throughout. */
    animation-range: exit 0% exit 100%;
  }

  /* Drill-down views (everything except the root) also get a shadow on
     their left edge during the transition so they feel like cards
     stacking over the previous view. */
  .Stack-view:not(:first-child) .Stack-viewContent {
    animation: parallax linear both, shadow-fade linear both;
    animation-timeline: view(inline), view(inline);
    /* parallax: only exit (the view sliding back as a deeper one comes in).
       shadow-fade: entry through exit (visible the whole time the view is
       transitioning, not when it's at rest). */
    animation-range: exit 0% exit 100%, entry 0% exit 100%;
  }

  @keyframes parallax {
    /* translateX(75%) and brightness(0.8) are examples — adjust to taste. */
    to {
      transform: translateX(75%);
      filter: brightness(0.8);
    }
  }

  @keyframes shadow-fade {
    /* Shadow ramps in during entry, holds across the middle of the
       gesture, and ramps out during exit — so it's only visible while
       the view is mid-transition, not when at rest. */
    0%, 100% { box-shadow: 0 0 1.5rem #0000; }
    25%, 75% { box-shadow: 0 0 1.5rem #0004; }
  }
}

注意:此效果在现代原生堆栈应用中很受欢迎,是一个很好的起点,但您可以根据需要自定义确切的视觉效果,以适应现有的过渡样式。

3. 模块状态

该堆栈在模块范围内跟踪四个状态:

const stack = document.querySelector('.Stack');

// Reference to the root view DOM element. The Stack starts empty, so
// this is null until the root view is created — either at init (step 8,
// when the URL is '/') or later by synthesizeRootEntry() (when the user
// landed on a deep link and then navigates back). Held as a mutable
// reference because other code (the scrollsnapchange handler, init, etc.)
// uses identity comparisons against it.
let rootView = null;

// Tracks which element to restore focus to when the user swipes back
// into a previous view. Keyed by the view element itself so entries
// are garbage-collected automatically when the view is pruned.
const returnFocus = new WeakMap();

// Maps history depth -> {urlPath, view}. We MUST maintain this map
// ourselves because the History API does not expose state for entries
// other than the current one — so when a view is pruned on swipe-back,
// we still need to remember which URL it represented in case the user
// later forward-navigates back into it.
const entriesByDepth = new Map();

// Tracked manually because history.state on a popstate event tells us
// the destination depth but not where we came from. We need both to
// compute the direction (back vs forward) and the distance.
let currentDepth = 0;

以及三个应用专属辅助函数,它们是应用中仅有的两个插入路由和视图渲染的位置:

// Resolve a URL path to the data your app needs to render the
// corresponding drill-down view, or return null for paths this section
// of the app does not handle (the root path '/', external links,
// unknown routes). resolveUrl() is for drill-down routes only — the
// root view is rendered separately by createRootView() below.
function resolveUrl(urlPath) {
  // Replace with your routing logic. For example, match `/view/:id`
  // and look the id up in your app state.
}

// Build the root (home) view of the stack. Application-specific content;
// preserve the .Stack-view / .Stack-viewContent wrapper structure (the
// inner element is required for the parallax — see step 2) and DO NOT
// render a back button — the root view has nothing behind it in the
// stack.
function createRootView() {
  const view = document.createElement('div');
  view.className = 'Stack-view';
  view.innerHTML = `
    <div class="Stack-viewContent">
      <!-- Root content. Include <a href> elements pointing at URL paths
           that resolveUrl() accepts, to enable drill-down from here. -->
    </div>
  `;
  return view;
}

// Build a drill-down view DOM element from the resolved route data.
// Customize the inner content freely, but DO preserve the .Stack-view
// / .Stack-viewContent wrapper structure and DO include a back button
// (the swipe gesture only works on touch).
function createDrillDownView(routeData) {
  const view = document.createElement('div');
  view.className = 'Stack-view';
  view.innerHTML = `
    <div class="Stack-viewContent">
      <header>
        <button class="back" aria-label="Back"></button>
        <!-- Title, breadcrumb, or other view chrome derived from
             routeData. -->
      </header>
      <main>
        <!-- View body, also from routeData. Include further <a href>
             elements pointing at URL paths that resolveUrl() also
             accepts, to enable additional drill-downs from this view. -->
      </main>
    </div>
  `;
  return view;
}

function getCurrentUrlPath() {
  return location.pathname;
}

4. 展开细目

下钻操作会按以下顺序执行四项操作:推送历史记录条目、构建新视图、附加新视图、平滑滚动到新视图。一旦贴靠完成,scrollsnapchange 处理程序(第 7 步)就会从该位置继续。

function drillDown(urlPath) {
  const routeData = resolveUrl(urlPath);
  if (!routeData) return;

  const newDepth = currentDepth + 1;
  // Push BEFORE creating the view so the URL is correct if anything
  // observing history (analytics, etc.) reads it during view creation.
  history.pushState({depth: newDepth}, '', urlPath);

  // pushState truncates forward entries in real browser history;
  // mirror that truncation in our depth map so we don't hold references
  // to views the user can no longer reach.
  for (const d of entriesByDepth.keys()) {
    if (d >= newDepth) entriesByDepth.delete(d);
  }
  currentDepth = newDepth;

  const newView = createDrillDownView(routeData);
  stack.appendChild(newView);
  entriesByDepth.set(newDepth, {urlPath, view: newView});

  // Scroll one viewport-width to the right. behavior: 'auto' defers to
  // the CSS `scroll-behavior` set in step 2, which is smooth unless
  // prefers-reduced-motion is set. The snap container locks onto the
  // new view; the scrollsnapchange listener (step 7) fires when the
  // snap settles.
  stack.scrollBy({left: stack.clientWidth, behavior: 'auto'});
}

5. 点击和返回按钮处理

拦截堆栈内的链接点击,并将其转换为下钻。保留辅助键行为,以便 cmd/中键点击仍可在新标签页中打开链接。

stack.addEventListener('click', (e) => {
  // Back button: defer to goBack() (defined below), which handles both
  // the normal in-app case and the deep-link case.
  if (e.target.closest('.back')) {
    goBack();
    return;
  }

  // Drill-down link.
  const link = e.target.closest('a');
  if (!link || !stack.contains(link)) return;
  // Let the browser handle modified clicks so users can open links
  // in new tabs / windows. e.button !== 0 filters out middle-clicks.
  if (e.metaKey || e.ctrlKey || e.shiftKey || e.button !== 0) return;

  const urlPath = new URL(link.href).pathname;
  const parentView = link.closest('.Stack-view');
  // If the URL isn't handled by this section of the app (resolveUrl
  // returns null), fall through so the browser navigates normally.
  if (!resolveUrl(urlPath) || !parentView) return;

  e.preventDefault();
  // Record which link the user activated so focus can be restored to
  // it when they swipe (or click) back into this view.
  returnFocus.set(parentView, link);
  drillDown(urlPath);
});

// Going back is usually just history.back(), but there's an important
// edge case: when the user lands directly on a deep-linked URL, there
// is no in-app history entry behind it. Calling history.back() in that
// situation would take them out of the app entirely. MANDATORY: detect
// this case and synthesize a root entry instead, so an in-app Back from
// a deep link lands on the root view and the platform Back from there
// returns the user to where they came from.
function goBack() {
  const atDeepLinkRoot = currentDepth === 0
    && entriesByDepth.get(0)?.view !== rootView;
  if (atDeepLinkRoot) {
    synthesizeRootEntry();
  } else {
    // history.back() fires popstate, which routes through
    // updateFromHistoryState (step 6) and scrolls the stack — the
    // same path a swipe-back converges on.
    history.back();
  }
}

function synthesizeRootEntry() {
  // Push a new history entry pointing at the root URL. This becomes the
  // entry the user "came from"; the original deep-linked entry is now
  // behind us, so platform Back from the root view will return there.
  const newDepth = currentDepth + 1;
  history.pushState({depth: newDepth}, '', '/');

  // Create the root view if it doesn't exist yet (we landed on a deep
  // link and never needed it before now), and insert it at the LEFT end
  // of the stack. Adjust scrollLeft by one viewport width so the user's
  // view doesn't visually jump — they should still be looking at the
  // deep-linked view until the scroll animation below runs.
  if (!rootView) {
    rootView = createRootView();
    stack.prepend(rootView);
    stack.scrollLeft += stack.clientWidth;
  }
  entriesByDepth.set(newDepth, {urlPath: '/', view: rootView});

  // Now scroll to the new entry (the root view). updateFromHistoryState
  // smooth-scrolls one step left, the parallax plays, and
  // scrollsnapchange fires when the root view settles.
  updateFromHistoryState(history.state);
}

6. 从历史记录同步 (popstate)

当用户使用浏览器/操作系统中的“后退”或“前进”按钮,或者 JavaScript 调用 history.back()/.go() 时,系统会触发 popstate。此处理程序是唯一一个在历史记录发生变化时滚动堆栈的路径。

window.addEventListener('popstate', (event) => {
  updateFromHistoryState(event.state);
});

function updateFromHistoryState(state, behaviorOverride) {
  const newDepth = state?.depth ?? 0;
  const urlPath = getCurrentUrlPath();

  // Ensure entriesByDepth has an entry for the destination depth.
  // If the URL changed (e.g. forward-nav into a previously-pruned
  // view), clear the cached view reference so the loop below rebuilds.
  const entry = entriesByDepth.get(newDepth) ?? {view: null};
  if (entry.urlPath !== urlPath) {
    entry.urlPath = urlPath;
    entry.view = urlPath === '/' ? rootView : null;
  }
  entriesByDepth.set(newDepth, entry);

  // Rebuild any views between root and the destination that were
  // pruned earlier (when the user swiped back past them). Without
  // this, forward-navigating to a previously-pruned view would have
  // no element to scroll to.
  for (let d = 0; d <= newDepth; d++) {
    const e = entriesByDepth.get(d);
    if (!e || e.view) continue;
    const routeData = resolveUrl(e.urlPath);
    if (!routeData) continue;
    const rebuilt = createDrillDownView(routeData);
    stack.appendChild(rebuilt);
    e.view = rebuilt;
  }

  currentDepth = newDepth;

  const targetView = entriesByDepth.get(newDepth)?.view;
  if (!targetView) return;

  // Compare destination index against current scroll position so we
  // can bail if they're already aligned. This is reached when the
  // scrollsnapchange handler below calls history.go() to sync history
  // after a swipe-back that already completed visually — there's
  // nothing more to scroll.
  const toIdx = [...stack.children].indexOf(targetView);
  const fromIdx = Math.round(stack.scrollLeft / stack.clientWidth);
  if (fromIdx === toIdx) return;

  // Pick a scroll behavior:
  //   - multi-step jumps (e.g. history.go(-3)): 'instant' to skip
  //     intermediate snap points — otherwise smooth-scrolling would
  //     fire scrollsnapchange for each one and do N rounds of
  //     state-transition work for no reason.
  //   - rightward (forward) single-step: 'instant'. Browser-forward is
  //     rare on the web and is often spurious (e.g. iOS Safari treats
  //     edge swipes as forward navigation, even with overscroll-behavior
  //     set). An instant swap reads as "snap" rather than a misleading
  //     drilldown animation the user didn't ask for. The user-initiated
  //     drill-down path (drillDown, step 4) is unaffected — it calls
  //     scrollBy directly and never reaches this code.
  //   - leftward (back) single-step: 'auto' so the CSS `scroll-behavior`
  //     (smooth unless prefers-reduced-motion is set — see step 2)
  //     applies. Back is the common, expected case and benefits from
  //     the animation.
  // NOTE: "forward" here means spatial direction (toIdx > fromIdx),
  // NOT depth direction. synthesizeRootEntry (step 5) pushes a new
  // depth but scrolls LEFT to the root view, which correctly reads as
  // back-style (smooth).
  const forward = toIdx > fromIdx;
  const multiStep = Math.abs(toIdx - fromIdx) > 1;
  const behavior = behaviorOverride ?? (forward || multiStep ? 'instant' : 'auto');
  stack.scrollTo({left: toIdx * stack.clientWidth, behavior});
}

7. scrollsnapchange:单一事实来源

每次吸附提交(无论是通过滑动、点击还是程序化滚动触发)后,浏览器都会在滚动容器上触发 scrollsnapchange 事件,并将新吸附的元素公开为 event.snapTargetInline(对于水平吸附)。将所有状态转换都放在这一个处理程序中,可使滑动路径、点击路径和 popstate 路径保持一致。

处理程序会被提取到独立的 onActiveViewChanged 函数中,以便后备(请参阅下文的“后备策略”)可以重复使用该函数,而无需复制逻辑。

function onActiveViewChanged(currentView) {
  // Walk the stack in DOM order to update each view's role:
  //  - Views at or before currentView stay in the DOM but get
  //    `inert` (except currentView) so focus, pointer events, and
  //    AT navigation cannot leak into views hidden behind the
  //    parallax.
  //  - Views after currentView are unreachable (the user swiped
  //    back past them) so we drop them from the DOM to free memory.
  //    Their urlPath stays in entriesByDepth so a later forward
  //    navigation can rebuild the view from scratch.
  let seenCurrent = false;
  for (const view of [...stack.children]) {
    if (seenCurrent) {
      for (const e of entriesByDepth.values()) {
        if (e.view === view) e.view = null;
      }
      view.remove();
    } else {
      // MANDATORY: inert non-current views. Without this, tabbing
      // and screen-reader navigation can reach content hidden behind
      // the parallax — a severe accessibility failure that's
      // invisible to sighted users.
      view.toggleAttribute('inert', view !== currentView);
      if (view === currentView) seenCurrent = true;
    }
  }

  // If the visible view's depth doesn't match `currentDepth`, the
  // user got here by swiping (not clicking) — sync history so the
  // browser back/forward buttons stay coherent with what's on screen.
  let currentViewDepth;
  for (const [d, e] of entriesByDepth) {
    if (e.view === currentView) currentViewDepth = d;
  }
  if (currentViewDepth !== undefined && currentViewDepth !== currentDepth) {
    // history.go fires popstate, which re-enters updateFromHistoryState.
    // That call's fromIdx === toIdx check bails out without scrolling.
    history.go(currentViewDepth - currentDepth);
  }

  // Restore focus on the now-active view:
  //  - If we recorded which link the user activated to drill out
  //    of this view, return focus there so a swipe-back lands them
  //    exactly where they left off.
  //  - Otherwise (a freshly-pushed drill-down view), move focus to
  //    the back button so keyboard users have an obvious next action.
  //  - preventScroll is REQUIRED: without it, .focus() scrolls the
  //    snap container to bring the focused element into view, which
  //    fights the snap and can land the user mid-snap.
  const stored = returnFocus.get(currentView);
  if (stored) {
    stored.focus({preventScroll: true});
    returnFocus.delete(currentView);
  } else if (currentView !== rootView) {
    currentView.querySelector('.back')?.focus({preventScroll: true});
  }
}

stack.addEventListener('scrollsnapchange', (event) => {
  // snapTargetInline is the element that was just snapped to on the
  // inline (horizontal) axis. For this stack — where each view is one
  // horizontal snap stop — that's the new active view.
  onActiveViewChanged(event.snapTargetInline);
});

网页加载时,网址可能已指向深层视图(共享链接、书签、深层网页上的刷新)。构建与网址匹配的初始视图(根视图或深层链接视图,但绝不能同时构建两者),将其附加到空堆栈,为深度 0 的历史记录条目添加种子,然后使用 behavior: 'instant' 运行初始滚动传递,这样视差效果就不会在首次绘制时呈现动画效果。

const initialUrlPath = getCurrentUrlPath();
const initialRouteData = resolveUrl(initialUrlPath);

// Build the initial view: a drill-down view if the URL maps to one,
// otherwise the root view. Whichever it is, that's the only view in
// the stack right now — the other will be created lazily by
// synthesizeRootEntry (step 5) or drillDown (step 4) if the user
// navigates to it.
let initialView;
if (initialRouteData) {
  initialView = createDrillDownView(initialRouteData);
} else {
  rootView = createRootView();
  initialView = rootView;
}
stack.appendChild(initialView);

entriesByDepth.set(0, {urlPath: initialUrlPath, view: initialView});
// replaceState attaches a `depth` to the entry the user landed on, so
// any subsequent pushState / popstate has a base depth to count from.
history.replaceState({depth: 0}, '');

updateFromHistoryState(history.state, 'instant');

最佳做法

  • 务必使用 scrollsnapchange 事件(具有 IntersectionObserver 后备机制 - 请参阅“后备策略”)作为“Active View 已更改”的可靠来源,而不是滚动事件坐标。吸附提交是唯一在滑动、点击、程序化滚动和 popstate 路径中始终触发的事件。
  • 务必对贴靠目标的子级应用转换,切勿对贴靠目标本身应用转换。对贴靠目标进行转换会反馈到滚动容器的贴靠几何图形中,并且滚动条会在手势中途出现故障。
  • 务必对除当前可见视图之外的每个视图应用 inert。如果没有此属性,焦点和屏幕阅读器导航会进入隐藏在视差效果背后的视图,这些视图对视力正常的用户不可见,但会导致严重的无障碍问题。
  • 务必在每次深入分析时推送历史记录条目并处理 popstate,以便操作系统级返回手势和浏览器后退/前进按钮正常运行。正是这种模式让应用感觉像原生应用。
  • 务必在滑动返回操作到达深度与 currentDepth 不匹配的视图时,通过 active-view-changed 处理程序协调历史记录。否则,后续的操作系统返回操作会将用户带到意想不到的位置,因为浏览器的历史记录光标与屏幕上的内容不同步。
  • 建议:从 DOM 中剪除用户滑过的视图。否则,长时间的深入分析会话可能会累积数十个分离的子树。entriesByDepth 中缓存的网址路径足以在向前导航返回到任何视图时重新构建该视图。
  • 务必在恢复堆栈内的焦点时调用 .focus({preventScroll: true})。默认的 preventScroll: false 会使浏览器将焦点目标滚动到视图中,这会与吸附容器发生冲突,并可能导致用户在吸附过程中停下来。
  • 务必保留内部链接上的 cmd/ctrl/中键点击功能,以便网址仍可共享并在新标签页中打开。
  • 务必将 behavior: 'instant' 用于多步历史记录跳转以及空间向前 popstate 转换 (toIdx > fromIdx)。否则,多步跳转会在每个中间快照处触发 scrollsnapchange,并执行 N 轮惰性/焦点/历史记录工作。前进 popstate 通常是虚假的,即使设置了 overscroll-behavior-x: none,iOS Safari 也会将边缘滑动视为浏览器前进,而即时交换比为用户未发起的“下钻”添加动画效果更不容易产生误导。用户发起的下钻路径 (drillDown) 不受影响,因为它会直接滚动,而不是通过 popstate 滚动。
  • 务必遵循 prefers-reduced-motion:仅在 @media (prefers-reduced-motion: no-preference) 内声明 scroll-behavior: smooth,并使用 behavior: 'auto'(而非 'smooth')调用 scrollTo / scrollBy,以便操作系统级偏好设置生效,而无需针对每次调用进行 JS 分支。对 behavior: 'smooth' 进行硬编码会绕过用户的设置。
  • 务必将真实的 <a href> 元素(而非 <button onclick> 或 <div>)呈现为下钻触发器。真正的锚点可免费获得悬停时网址预览、可分享性、中键点击、屏幕阅读器角色和 SEO。
  • 务必在每个下钻视图中添加一个明确的返回按钮。滑动手势仅适用于触控操作,键盘、指针和桌面设备用户需要可见的提示。
  • 请勿从 popstate 处理程序调用 history.pushState,因为这会在用户尝试返回时推送新条目,并破坏浏览器的返回按钮。
  • 当滚动驱动的动画可用时,请勿使用 scroll 事件监听器驱动视差。CSS 路径在合成器上运行;JS 滚动监听器在主线程上运行,并且会在手势期间明显丢帧。
  • 请勿在滑动返回后更改从 DOM 中移除的视图。将 entriesByDepth 视为规范记录:经过修剪的条目具有 view: null,并会根据需要在 updateFromHistoryState 中重新构建。

后备策略

可能需要后备方案的功能包括 scroll-snap-events 和 scroll-driven-animations,这两项功能都具有强大的后备方案或渐进增强功能,可安全地用于此用例:

滚动贴靠事件

scrollsnapchange 事件是检测“Active View 已更改”的最简洁方式,即堆栈上有一个监听器,每次快照提交时都会触发一次。在不支持该功能的浏览器中,可以使用 IntersectionObserver 观察每个视图,以实现相同的效果,从而在堆栈中实现完全可见性。后备路径会分派到主要路径使用的同一 onActiveViewChanged 函数,因此所有状态转换逻辑都集中在一个位置。

// MANDATORY when supporting browsers that haven't shipped scroll-snap-events
// yet. Check `HTMLElement.prototype` (not `window` or `document`) — the
// event handler IDL attribute is added to the prototype when the feature
// is supported, regardless of whether any element has the handler set.
if (!('onscrollsnapchange' in HTMLElement.prototype)) {
  const viewObserver = new IntersectionObserver((entries) => {
    for (const entry of entries) {
      // threshold:1 only fires for fully-visible entries, but the
      // observer also emits a "leaving" entry per view that drops below
      // ratio 1. Filter to the entering side, which is the snap-commit
      // moment we're trying to detect.
      if (entry.intersectionRatio === 1) {
        onActiveViewChanged(entry.target);
      }
    }
  }, {root: stack, threshold: 1});

  // Auto-observe every .Stack-view as it's added to the stack, and stop
  // observing as it's removed. Using a MutationObserver lets the primary
  // code (drillDown, updateFromHistoryState, synthesizeRootEntry, init)
  // stay free of fallback wiring.
  new MutationObserver((mutations) => {
    for (const m of mutations) {
      for (const node of m.addedNodes) {
        if (node.classList?.contains('Stack-view')) viewObserver.observe(node);
      }
      for (const node of m.removedNodes) {
        if (node.classList?.contains('Stack-view')) viewObserver.unobserve(node);
      }
    }
  }).observe(stack, {childList: true});

  // Catch up to any views already in the stack at the time this code
  // runs (typically the initial view appended in step 8).
  for (const view of stack.children) viewObserver.observe(view);
}

滚动驱动的动画

滚动驱动的视差/变暗/阴影效果是导航核心之上的渐进增强。CSS @supports (animation-timeline: view()) 门控(如第 2 步所示)会将动画限制在支持的浏览器中;在其他所有浏览器中,视图只是在贴靠停止点之间切换,没有过渡效果。即使没有视差效果,该组件也能正常运行,吸附、历史记录同步、焦点管理和 inert 仍可正常运行。

如果需要为旧版基准目标提供视差后备方案,请将 scroll 监听器附加到堆栈,并编写一个 CSS 自定义属性来描述每个视图在滚动条中的进度,然后通过该属性驱动 transform 和 filter:

if (!CSS.supports('animation-timeline: view()')) {
  stack.addEventListener('scroll', () => {
    const viewWidth = stack.clientWidth;
    for (const view of stack.children) {
      // Progress: 0 when this view is centered, 1 when it has fully
      // exited to the left. Matches the @keyframes mapping above.
      const offsetLeft = view.offsetLeft - stack.scrollLeft;
      const progress = Math.min(1, Math.max(0, -offsetLeft / viewWidth));
      const content = view.querySelector('.Stack-viewContent');
      content.style.transform = `translateX(${progress * 75}%)`;
      content.style.filter = `brightness(${1 - progress * 0.2})`;
    }
  });
}