# 侧滑压栈转场（Push navigation transition）

- 俗称：push 页面跳转；push 和 present 的区别；iOS 导航压栈；详情页从右边滑进来；移动端右入左出导航；侧滑压栈
- 用在：页面切换（工具和应用、移动端网页、个人网站）
- 触发：点击
- 感觉：利落、柔和
- 版本：1，更新于 2026-12-02

## 原理

两页叠在同一裁剪容器内，通过 Web Animations API 同时动画化单个 translate 属性：新页从 100% 滑到 0%，旧页同步向左视差退移 parallax% 并叠一层轻暗遮罩；非当前页加 inert 和 aria-hidden，支持 Esc 返回，减少动态时直接切换视图。

适合：移动端列表进详情、设置项进子页面等同一任务路径的层级下钻；若只是临时打断流程办一件独立小事（如新建、登录），改用「底部卡片弹出（Present）」。

## 参数

| 参数名 | 含义 | 默认值 | 建议范围 |
|---|---|---|---|
| `duration` | 时长 | 420ms | 200–700ms |
| `parallax` | 旧页退移 | 28% | 10–50% |
| `easing` | 缓动 | cubic-bezier(0.32, 0.72, 0, 1) | — |

## 质量要求

- 开启"减少动态"时：跳过滑动与视差退移，点击直接切换当前视图并保留焦点与 inert 管理。
- 手机上：与桌面一致，贴合 iOS 导航压栈手感；支持返回按钮与 Esc 返回上一层。
- 动画只在播放时改变元素；脚本出错或没有执行时，内容照样可见（不要先用 CSS 把内容藏起来再等脚本显示）。

## 提示词（可以直接交给 AI）

```text
请在我的项目里给页面切换加上「侧滑压栈转场」（Push navigation transition）效果：两页叠在同一裁剪容器内，通过 Web Animations API 同时动画化单个 translate 属性：新页从 100% 滑到 0%，旧页同步向左视差退移 parallax% 并叠一层轻暗遮罩；非当前页加 inert 和 aria-hidden，支持 Esc 返回，减少动态时直接切换视图。
参数：时长 420ms，旧页退移 28%，缓动 cubic-bezier(0.32, 0.72, 0, 1)。
要求：保留原有的内容和布局；系统开启"减少动态"时直接显示最终状态；脚本出错或没有执行时内容仍然可见。
参考：https://donglang.linter.top/effects/push-navigation.md（原理、参数和参考代码）
```

## 参考代码

HTML 结构：

```html
<div class="push-viewport" data-push-viewport>
  <section class="push-page" data-push-root aria-label="列表页">
    <header>
      <strong>收件箱</strong>
    </header>
    <ul>
      <li><button type="button" data-push-go>设计评审纪要 →</button></li>
      <li><button type="button" data-push-go>动效参数规范 →</button></li>
    </ul>
  </section>

  <div class="push-scrim" data-push-scrim aria-hidden="true"></div>

  <section class="push-page" data-push-detail inert aria-hidden="true" aria-label="详情页">
    <header>
      <button type="button" data-push-pop>← 返回</button>
      <strong>设计评审纪要</strong>
    </header>
    <p>同一路径往下钻时，详情页从右侧整屏滑入，列表页向左轻退提示层级深度。</p>
  </section>
</div>
```

CSS：

```css
/* 侧滑压栈转场（Push navigation transition）· 参考 CSS */
.push-viewport {
  --push-duration: 420ms;
  --push-parallax: 28%;
  --push-easing: cubic-bezier(0.32, 0.72, 0, 1);
  position: relative;
  overflow: hidden;
  width: 100%;
  height: 100%;
}

.push-page {
  position: absolute;
  inset: 0;
  background: var(--push-bg, #ffffff);
  will-change: translate;
}

.push-page[data-push-detail] {
  translate: 100% 0;
  box-shadow: -12px 0 28px rgb(20 21 25 / 0.14);
}

.push-viewport[data-pushed="true"] .push-page[data-push-root] {
  translate: calc(-1 * var(--push-parallax, 28%)) 0;
}

.push-viewport[data-pushed="true"] .push-page[data-push-detail] {
  translate: 0 0;
}

.push-scrim {
  position: absolute;
  inset: 0;
  background: rgb(20 21 25);
  opacity: 0;
  pointer-events: none;
}

.push-viewport[data-pushed="true"] .push-scrim {
  opacity: 0.18;
}
```

JS（原生，不依赖任何库）：

```js
// 侧滑压栈转场（Push navigation transition）· 原生 JS，不依赖任何库。
// 用法：const ctl = pushNavigation(viewportEl, { duration: 420, parallax: 28, easing: '...' });
//       调 ctl.push() 进入下一级、ctl.pop() 返回上一级，销毁调 ctl.destroy()。

export function pushNavigation(root, {
  duration = 420,
  parallax = 28,
  easing = 'cubic-bezier(0.32, 0.72, 0, 1)',
  ignoreReducedMotion = false,
} = {}) {
  if (!(root instanceof Element)) return null;
  const rootPage = root.querySelector('[data-push-root]');
  const detailPage = root.querySelector('[data-push-detail]');
  const scrim = root.querySelector('[data-push-scrim]');
  if (!rootPage || !detailPage) return null;

  const dur = Number(duration) || 420;
  const shift = Number(parallax) || 28;
  const easeStr = String(easing);
  const reduceQuery = typeof matchMedia === 'function' ? matchMedia('(prefers-reduced-motion: reduce)') : null;
  const isReduced = () => Boolean(reduceQuery?.matches && !ignoreReducedMotion);

  root.style.setProperty('--push-duration', `${dur}ms`);
  root.style.setProperty('--push-parallax', `${shift}%`);
  root.style.setProperty('--push-easing', easeStr);

  let pushed = root.getAttribute('data-pushed') === 'true';
  let anims = [];
  let returnTo = null;
  let destroyed = false;

  const cancelAnims = () => {
    anims.forEach((a) => a.cancel());
    anims = [];
  };

  const syncA11y = (isPushed) => {
    root.setAttribute('data-pushed', isPushed ? 'true' : 'false');
    if (isPushed) {
      rootPage.setAttribute('inert', '');
      rootPage.setAttribute('aria-hidden', 'true');
      detailPage.removeAttribute('inert');
      detailPage.removeAttribute('aria-hidden');
    } else {
      detailPage.setAttribute('inert', '');
      detailPage.setAttribute('aria-hidden', 'true');
      rootPage.removeAttribute('inert');
      rootPage.removeAttribute('aria-hidden');
    }
  };

  syncA11y(pushed);

  const push = () => {
    if (destroyed || pushed) return;
    returnTo = document.activeElement instanceof HTMLElement ? document.activeElement : null;
    pushed = true;
    cancelAnims();
    syncA11y(true);

    if (!isReduced()) {
      const timing = { duration: dur, easing: easeStr, fill: 'both' };
      anims = [
        rootPage.animate([{ translate: '0% 0px' }, { translate: `${-shift}% 0px` }], timing),
        detailPage.animate([{ translate: '100% 0px' }, { translate: '0% 0px' }], timing),
        ...(scrim ? [scrim.animate([{ opacity: 0 }, { opacity: 0.18 }], timing)] : []),
      ];
      Promise.all(anims.map((a) => a.finished)).then(() => {
        if (!destroyed) anims = [];
      }).catch(() => undefined);
    }

    const backBtn = detailPage.querySelector('[data-push-pop], button, a[href]');
    if (backBtn instanceof HTMLElement && backBtn.tabIndex !== -1) backBtn.focus({ preventScroll: true });
    root.dispatchEvent(new CustomEvent('pushchange', { detail: { pushed: true }, bubbles: true }));
  };

  const pop = () => {
    if (destroyed || !pushed) return;
    pushed = false;
    cancelAnims();

    const finishPop = () => {
      if (destroyed) return;
      syncA11y(false);
      if (returnTo && returnTo.isConnected && returnTo.tabIndex !== -1) {
        returnTo.focus({ preventScroll: true });
      }
      returnTo = null;
      root.dispatchEvent(new CustomEvent('pushchange', { detail: { pushed: false }, bubbles: true }));
    };

    if (isReduced()) {
      finishPop();
      return;
    }

    rootPage.removeAttribute('inert');
    rootPage.removeAttribute('aria-hidden');
    const timing = { duration: dur, easing: easeStr, fill: 'both' };
    anims = [
      rootPage.animate([{ translate: `${-shift}% 0px` }, { translate: '0% 0px' }], timing),
      detailPage.animate([{ translate: '0% 0px' }, { translate: '100% 0px' }], timing),
      ...(scrim ? [scrim.animate([{ opacity: 0.18 }, { opacity: 0 }], timing)] : []),
    ];
    Promise.all(anims.map((a) => a.finished)).then(() => {
      anims = [];
      finishPop();
    }).catch(() => undefined);
  };

  const pushBtns = [...root.querySelectorAll('[data-push-go]')];
  const popBtns = [...root.querySelectorAll('[data-push-pop]')];
  const onPushClick = () => push();
  const onPopClick = () => pop();
  const onKeyDown = (ev) => {
    if (ev.key === 'Escape' && pushed) {
      ev.preventDefault();
      pop();
    }
  };

  pushBtns.forEach((btn) => btn.addEventListener('click', onPushClick));
  popBtns.forEach((btn) => btn.addEventListener('click', onPopClick));
  root.addEventListener('keydown', onKeyDown);

  return {
    push,
    pop,
    isPushed: () => pushed,
    destroy() {
      if (destroyed) return;
      destroyed = true;
      cancelAnims();
      pushBtns.forEach((btn) => btn.removeEventListener('click', onPushClick));
      popBtns.forEach((btn) => btn.removeEventListener('click', onPopClick));
      root.removeEventListener('keydown', onKeyDown);
      root.style.removeProperty('--push-duration');
      root.style.removeProperty('--push-parallax');
      root.style.removeProperty('--push-easing');
    },
  };
}
```

## 出处

- 本站原创实现：参考 iOS 导航压栈（Push）的空间视差规律自研原生 JS + CSS 实现，未使用第三方代码
