# 横向滚动画廊（Horizontal scroll gallery）

- 俗称：往下滚页面作品图片却横着往左走；作品集的横向滚动画廊；向下滑动时一排项目横向移动；纵向滚轮控制横排作品展示
- 用在：卡片列表、图片（作品集、品牌官网）
- 触发：滚动
- 感觉：高级、利落
- 版本：1，更新于 2026-11-13

## 原理

纵向滚动框里留出横向溢出距离除以速度的跑道；窗口用 sticky 留在顶上，横排轨道按 scrollTop 乘速度向左平移，最多挪到最后一张刚好露全；滚轮和触摸用原生滚动，方向键也能走，尺寸变化重新量，无脚本和减少动态时变为静态网格。

适合：作品集和案例展示：用一段向下滚动的距离，横着看完一排作品；到最后一张后继续往下读。

## 参数

| 参数名 | 含义 | 默认值 | 建议范围 |
|---|---|---|---|
| `speed` | 横向移动的速度 | 1倍 | 0.5–2倍 |

## 质量要求

- 开启"减少动态"时：不固定窗口、不横向平移，按静态网格排列全部作品。
- 手机上：手指上下滑动原生滚动框；最后一张后可接着滚页面；减少动态时直接看静态排列。
- 动画只在播放时改变元素；脚本出错或没有执行时，内容照样可见（不要先用 CSS 把内容藏起来再等脚本显示）。

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

```text
请在我的项目里给卡片列表加上「横向滚动画廊」（Horizontal scroll gallery）效果：纵向滚动框里留出横向溢出距离除以速度的跑道；窗口用 sticky 留在顶上，横排轨道按 scrollTop 乘速度向左平移，最多挪到最后一张刚好露全；滚轮和触摸用原生滚动，方向键也能走，尺寸变化重新量，无脚本和减少动态时变为静态网格。
参数：横向移动的速度 1倍。
要求：保留原有的内容和布局；系统开启"减少动态"时直接显示最终状态；脚本出错或没有执行时内容仍然可见。
参考：https://donglang.linter.top/effects/horizontal-scroll.md（原理、参数和参考代码）
```

## 参考代码

HTML 结构：

```html
<!-- 为每个作品保留文字说明；没有脚本时按普通网格展示。 -->
<section class="hg" tabindex="0" aria-label="作品画廊：上下滚动，或使用方向键浏览">
  <div class="hg-runway"><div class="hg-pin"><div class="hg-track">
    <article><h2>山间旅店</h2><p>空间与品牌设计</p></article>
    <article><h2>海边书店</h2><p>阅读与生活方式</p></article>
    <article><h2>城市漫游</h2><p>移动端产品设计</p></article>
  </div></div></div>
</section>
<script type="module">
  import { horizontalScroll } from './horizontal-scroll.js';
  const gallery = horizontalScroll(document.querySelector('.hg'), { speed: 1 });
  // 路由卸载时 gallery.destroy()。
</script>
```

CSS：

```css
/* 无脚本先是静态网格；增强后才把纵向距离换成横向。容器可自行覆盖 --hg-height。 */
.hg { --hg-height: 70vh; }
.hg-track { display: grid; gap: 20px; }
.hg-track > * { min-width: 0; }
.hg.hg-js { position: relative; height: var(--hg-height); overflow: auto; }
.hg-js .hg-pin { position: sticky; top: 0; height: var(--hg-vh); overflow: hidden; }
.hg-js .hg-track { display: flex; width: max-content; height: 100%; }
.hg-js .hg-track > * { flex: 0 0 auto; width: min(80vw, 640px); }
.hg:focus-visible { outline: 2px solid currentColor; outline-offset: -3px; }
@media (prefers-reduced-motion: reduce) {
  .hg.hg-js:not(.hg-force) { height: auto; overflow: visible; }
  .hg-js:not(.hg-force) .hg-pin { position: static; height: auto; overflow: visible; }
  .hg-js:not(.hg-force) .hg-track { display: grid; width: auto; height: auto; translate: none !important; }
  .hg-js:not(.hg-force) .hg-track > * { width: auto; }
}
```

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

```js
// 横向滚动画廊 · 原生 JS。本站原创实现，没有复制第三方代码。
// .hg 是有高度的纵向滚动框，里面 .hg-runway > .hg-pin > .hg-track；轨道的子项横排。
// 普通滚轮和触摸仍是浏览器的纵向滚动，sticky 窗口里的轨道按 scrollTop × speed 往左挪。
// speed 是横向距离 / 纵向距离。ResizeObserver 重量轨道和窗口；零尺寸、只有一项时不制造空白跑道。
// 在 root 上设 tabindex="0" 和 aria-label；方向键、PageUp/Down、Home/End 都能操作，不截获内部表单和链接的按键。
// 无 JS、减少动态时显示静态网格，不锁住页面滚动。ignoreReducedMotion 只给用户主动重播的演示用。
// 返回 update(), destroy()；重复安装会拆旧的；destroy 取消帧、摘监听并还原样式。
const instances = new WeakMap();
export function horizontalScroll(root, {
  speed = 1,
  ignoreReducedMotion = false,
} = {}) {
  instances.get(root)?.destroy();
  const track = root.querySelector('.hg-track');
  const runway = root.querySelector('.hg-runway');
  if (!track || !runway || !Number.isFinite(speed) || speed <= 0) return null;
  const saved = [root, track, runway].map(el => [el, el.getAttribute('style')]);
  const media = matchMedia('(prefers-reduced-motion: reduce)');
  let dead = false, frame = 0;
  let max = 0;
  const restore = () => saved.forEach(([el, style]) => {
    if (style === null) { void el.getAttribute('style'); el.removeAttribute('style'); }
    else el.setAttribute('style', style);
  });
  const update = () => {
    if (dead) return;
    const reduce = media.matches && !ignoreReducedMotion;
    root.classList.toggle('hg-js', !reduce);
    root.classList.toggle('hg-force', ignoreReducedMotion);
    if (reduce) { restore(); return; }
    const height = root.clientHeight;
    if (!(root.clientWidth > 0 && height > 0)) return;
    max = Math.max(0, track.scrollWidth - root.clientWidth);
    const h = `${height}px`, length = `${height + max / speed}px`;
    if (root.style.getPropertyValue('--hg-vh') !== h) root.style.setProperty('--hg-vh', h);
    if (runway.style.height !== length) runway.style.height = length;
    track.style.translate = `${-Math.min(max, Math.max(0, root.scrollTop * speed))}px 0px`;
  };
  const schedule = () => { if (!dead && !frame) frame = requestAnimationFrame(() => { frame = 0; update(); }); };
  const key = (e) => {
    if (e.target !== root || e.altKey || e.metaKey || e.ctrlKey) return;
    const step = root.clientHeight * 0.8;
    const value = { ArrowDown: root.scrollTop + step, ArrowRight: root.scrollTop + step, PageDown: root.scrollTop + step,
      ArrowUp: root.scrollTop - step, ArrowLeft: root.scrollTop - step, PageUp: root.scrollTop - step,
      Home: 0, End: root.scrollHeight - root.clientHeight }[e.key];
    if (value === undefined) return;
    e.preventDefault(); root.scrollTop = value; update();
  };
  root.addEventListener('scroll', schedule, { passive: true });
  root.addEventListener('keydown', key);
  media.addEventListener('change', schedule);
  const observer = new ResizeObserver(schedule);
  observer.observe(root); observer.observe(track);
  update();
  const ctl = { update, destroy() {
    if (dead) return; dead = true; cancelAnimationFrame(frame);
    observer.disconnect(); root.removeEventListener('scroll', schedule); root.removeEventListener('keydown', key);
    media.removeEventListener('change', schedule);
    root.classList.remove('hg-js', 'hg-force'); restore();
    if (instances.get(root) === ctl) instances.delete(root);
  } };
  instances.set(root, ctl); return ctl;
}
```

## 出处

- 同类效果见第四批清单中的 Animation Handbook horizontal-scroll 收录名；本站独立实现，没有复制代码、文字或图片；sticky 跑道、速度和键盘处理均为本站编写
