# 滚动视差（Parallax scrolling）

- 俗称：往下滑时背景比前面的内容动得慢；滚动时远处的东西动得慢，有前后层次；背景跟着滚动慢慢移；滚动有纵深感的视差
- 用在：背景、图片（个人网站、作品集、品牌官网）
- 触发：滚动
- 感觉：高级、戏剧化
- 版本：1，更新于 2026-10-17

## 原理

每一层按所在区块离屏幕中间多远往回拉一点：越远的层拉得越多，看起来比滚动慢；区块在屏幕正中时各层都在原位。

适合：首屏的插画或大图、分隔用的风景带；层次少一点（两三层），只放在一两个区块上。

## 参数

| 参数名 | 含义 | 默认值 | 建议范围 |
|---|---|---|---|
| `speed` | 远处那层比滚动慢多少 | 30% | 0–80% |

## 质量要求

- 开启"减少动态"时：不做视差，各层都在原位，跟着页面一起滚。
- 手机上：照常跟着手指滚动，惯性滚动时也跟得上；手机屏幕矮，速度可以调小一点。
- 动画只在播放时改变元素；脚本出错或没有执行时，内容照样可见（不要先用 CSS 把内容藏起来再等脚本显示）。

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

```text
请在我的项目里给背景加上「滚动视差」（Parallax scrolling）效果：每一层按所在区块离屏幕中间多远往回拉一点：越远的层拉得越多，看起来比滚动慢；区块在屏幕正中时各层都在原位。
参数：远处那层比滚动慢多少 30%。
要求：保留原有的内容和布局；系统开启"减少动态"时直接显示最终状态；脚本出错或没有执行时内容仍然可见。
参考：https://donglang.linter.top/effects/parallax.md（原理、参数和参考代码）
```

## 参考代码

HTML 结构：

```html
<!-- 滚动视差：区块里标了 data-depth 的层会动，1 是最远的。层里放自己的图（远景、近景），区块要有高度 -->
<section class="hero px-section" style="height: 70vh">
  <div class="px-layer" data-depth="1" style="background: url(远景.jpg) center / cover"></div>
  <div class="px-layer" data-depth="0.5" style="background: url(近景.png) center bottom / cover no-repeat"></div>
  <h1 style="position: relative">山海手记</h1>
</section>
<script type="module">
  import { parallax } from './parallax.js';
  parallax(document.querySelectorAll('.px-section'));
</script>
```

CSS：

```css
/* 滚动视差（Parallax scrolling）的样式，配合 parallax.js。区块裁掉伸出去的层；
   铺满区块的背景层上下各多出 --px-reach（由 parallax.js 按屏幕高、区块高、速度和层的深度算好），往回拉的时候不露空白。
   层里放自己的图：用 background-image，或者放一张 object-fit: cover 的图片。 */
.px-section {
  position: relative;
  overflow: hidden;
}
.px-layer {
  position: absolute;
  inset: calc(-1 * var(--px-reach, 0px)) 0;
  will-change: translate;
}
@media (prefers-reduced-motion: reduce) {
  .px-layer { will-change: auto; }
}
```

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

```js
// 滚动视差（Parallax scrolling）· 原生 JS，不依赖任何库。
// 改写自 Animation Handbook 的 Parallax Scrolling（MIT License，Copyright (c) 2026 Matin Monshizadeh）：远的层动得少、近的层动得多；
// 滚动事件里只排一次逐帧更新（同一帧里滚动再多次也只算一次）。StyleKit 的 parallax-float（MIT）按元素离屏幕的距离乘速度，本站也是这样算。
// sections 是一个或一组区块，区块里标了 data-depth 的元素就是会动的层（配合 parallax.css）：
//   data-depth="1" 比滚动慢"速度"那么多（远处），0.5 慢一半，0 不动；写负数就比滚动还快（近处）。
// 每一层按"所在区块的中心离屏幕中心多远"往回拉：区块正好在屏幕中间时，各层都在原位。
// 用 translate 属性，不碰层上原来的 transform。root 是滚动的容器，默认整个页面（window）；放在自己会滚动的框里时传那个框。
// 返回 { update(), destroy() }。滚动、改窗口大小、区块或滚动框自己变高时都会重算。
// 开启"减少动态"时：各层都在原位，不跟着滚动动。脚本没执行时也在原位，内容完整。
// 铺满区块的层要比区块大一圈，往回拉时才不露出空白。要多出多少由这里算好，写在层的 --px-reach 上（parallax.css 用它把层上下撑大）：
// 区块的边露在屏幕里时，层最多被拉开多少：远处的层（深度为正）是 (屏幕高 - 区块高) ÷ 2 × 速度 × 深度，区块比屏幕高时不用多出；
// 比滚动还快的层（深度为负）是 (屏幕高 + 区块高) ÷ 2 × 速度 × |深度|。
// ignoreReducedMotion 只给演示用。
/**
 * @param {Element | Iterable<Element>} sections
 * @param {{ speed?: number, root?: Window | HTMLElement, ignoreReducedMotion?: boolean }} [options]
 */
export function parallax(sections, {
  speed = 30,
  root = window,
  ignoreReducedMotion = false,
} = {}) {
  const reduce = !ignoreReducedMotion && matchMedia('(prefers-reduced-motion: reduce)').matches;
  const list = sections instanceof Element ? [sections] : [...sections];
  const layers = list.flatMap((section) => [...section.querySelectorAll('[data-depth]')]
    .map((el) => ({ el, section, depth: Number(el.dataset.depth) || 0, before: el.style.translate, reach: -1 })));
  if (reduce || !layers.length) return { update() {}, destroy() {} };

  // 屏幕（或滚动框里看得见的那一块）的上边和高度
  const view = () => {
    if (root === window) return [0, innerHeight];
    const r = root.getBoundingClientRect();
    return [r.top + root.clientTop, root.clientHeight];
  };
  const update = () => {
    const [top, height] = view();
    const middle = top + height / 2;
    layers.forEach((layer) => {
      const { el, section, depth } = layer;
      const r = section.getBoundingClientRect();
      const offset = -(r.top + r.height / 2 - middle) * (speed / 100) * depth;
      el.style.translate = `0 ${offset.toFixed(2)}px`;
      // 要多出多少只在屏幕或区块的高度变了时才变；变了才写，免得每帧都改样式
      const span = depth >= 0 ? Math.max(0, height - r.height) : height + r.height;
      const reach = Math.ceil((span / 2) * (speed / 100) * Math.abs(depth)) + 1;
      if (reach !== layer.reach) {
        layer.reach = reach;
        el.style.setProperty('--px-reach', `${reach}px`);
      }
    });
  };
  let ticking = false;
  const onScroll = () => {
    if (ticking) return;
    ticking = true;
    requestAnimationFrame(() => {
      ticking = false;
      update();
    });
  };
  root.addEventListener('scroll', onScroll, { passive: true });
  window.addEventListener('resize', onScroll, { passive: true });
  // 区块、滚动框自己变高（图片加载完、内容变了、字体换了）时，没有滚动也没有改窗口大小，也要重算位移和要多出多少
  const resized = new ResizeObserver(onScroll);
  list.forEach((section) => resized.observe(section));
  if (root !== window) resized.observe(root);
  update();

  return {
    update,
    destroy() {
      root.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
      resized.disconnect();
      layers.forEach(({ el, before }) => { el.style.translate = before; el.style.removeProperty('--px-reach'); });
    },
  };
}
```

## 出处

- Animation Handbook · Parallax Scrolling（https://github.com/matinmonshizadeh/animation-handbook/tree/main/animations/01-scroll-based/parallax-scrolling，MIT）：改写自它的做法（远的层动得少、近的层动得多；滚动事件里每帧只排一次更新；用位移，减少动态时各层在原位）；改成按区块中心离屏幕中心的距离乘速度（StyleKit 的 parallax-float 也是按距离乘速度），用 translate 属性不碰原来的 transform，可以放在自己会滚动的框里
