中文
山海手记
Scroll · Vanilla JS + CSS

Parallax scrolling

滚动视差

Move foreground and background at different scroll speeds.

Also searched as: 往下滑时背景比前面的内容动得慢, 滚动时远处的东西动得慢,有前后层次, 背景跟着滚动慢慢移, 滚动有纵深感的视差

AI Markdown (.md)
Placement
Background, Image
Mood
Refined, Dramatic
Trigger
Scroll
Site types
个人网站, 作品集, 品牌官网

How it works & accessibility

Map scroll progress to different translate distances for foreground and background layers.

Best for: Background, Image (Scroll).

Reduced motion: 不做视差,各层都在原位,跟着页面一起滚

Mobile & touch: 照常跟着手指滚动,惯性滚动时也跟得上;手机屏幕矮,速度可以调小一点

Key parameters

ParameterKeyDefaultRangeNotes
远处那层比滚动慢多少speed30%——

Ready-to-paste AI prompt

Add “Parallax scrolling” to the background in my project: Map scroll progress to different translate distances for foreground and background layers.
Parameters: speed: 30%.
Preserve existing content and layout. Respect prefers-reduced-motion by showing the final state. Content must remain visible if JavaScript fails or is disabled.
Reference: https://donglang.linter.top/effects/parallax.md (canonical specification and reference code).

Dependency-free reference code

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; }
}
JavaScript
// 滚动视差(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'); });
    },
  };
}
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>

Shown once per release · Always available in changelog