堆疊下鑽

總覽

堆疊細目是階層式導覽模式,在行動應用程式中很常見,啟用連結後,新的全螢幕檢視畫面會疊在先前的檢視畫面上方。檢視畫面的內容由應用程式定義,例如設定子頁面、動態消息中的討論串、檔案瀏覽器中的資料夾、圖片庫中的詳細資料頁面等。使用者只要將目前的檢視畫面往右滑出螢幕,或輕觸返回按鈕,即可返回。瀏覽器歷史記錄會保持同步,因此 OS 層級的返回手勢、深層連結和返回瀏覽功能都能一致運作。

本指南會將堆疊實作為:

  • 水平 CSS 捲動貼齊容器,其中每個檢視畫面都是一個貼齊停靠點。向下展開會附加新檢視畫面,並順暢捲動至該畫面;滑動返回手勢由瀏覽器原生處理,不需使用指標事件 JavaScript,即可免費追蹤動量、速度和中斷。
  • 堆疊上的 scrollsnapchange 事件監聽器,會在貼齊目標變更時觸發。這會做為「Active View 已變更」的單一事實來源,因此滑動、點擊、程式輔助捲動和 popstate 路徑都會匯集到一個回呼中,用於更新 inert、還原焦點、刪除使用者滑過的檢視畫面,以及協調瀏覽記錄。
  • pushState/popstate 整合,因此每次向下鑽研都會新增記錄項目、OS 層級的返回手勢可正常運作,且深層連結會直接開啟正確的檢視畫面。
  • 每個檢視畫面上都有一個 (選用) 捲動驅動的 view() 動畫,可產生與滑動手勢直接相關的視差 + 變暗 + 陰影效果,因此可見的動作是由使用者的手指驅動,而非補間動畫。

這種做法比 JavaScript 驅動的 transform 動畫更合適,因為貼齊機制可讓使用者直接透過手勢控制面板位置 (由手指驅動,而非補間動畫),並符合使用者對原生行動應用程式的互動模式預期。

導入作業

1. 標記

靜態 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)

當使用者點選瀏覽器/OS 的返回或前進按鈕,或 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 備用事件,請參閱「備用策略」) 做為「有效檢視畫面已變更」的可靠資料來源,而非捲動事件座標。貼齊提交是唯一會在滑動、點擊、程式輔助捲動和 popstate 路徑中持續觸發的事件。
  • 務必對貼齊目標的子項套用轉換,切勿對貼齊目標本身套用轉換。對貼齊目標進行轉換,會回饋到捲動容器的貼齊幾何圖形,而捲動器會在手勢中途發生錯誤。
  • 務必將 inert 套用至目前可見檢視畫面以外的所有檢視畫面。如果沒有這項設定,焦點和螢幕閱讀器導覽功能就會洩漏到視差效果後方的隱藏檢視畫面,雖然視力正常的使用者看不到,但這會造成嚴重的無障礙功能問題。
  • 務必在每次向下展開時推送記錄項目,並處理 popstate,確保 OS 層級的返回手勢和瀏覽器返回/前進按鈕正常運作。這就是讓模式感覺像原生應用程式的原因。
  • 務必在滑動返回至深度與 currentDepth 不符的檢視畫面時,從 active-view-changed 處理常式中協調記錄。如果沒有這項設定,後續的 OS 返回動作會將使用者帶往非預期的位置,因為瀏覽器的記錄游標與畫面上的內容不同步。
  • 務必從 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,這樣 OS 層級偏好設定就會生效,不必為每次呼叫建立 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})`;
    }
  });
}