Zoom Parallax
隨捲動放大穿越的圖組,多張圖片以中心為原點各自加速縮放,形成飛入景深的視差效果。
載入預覽⋯
Playground
即時調整 props、程式碼片段同步更新——直接試出你要的樣子再複製。
<ZoomParallax />
安裝
npx shadcn@latest add https://webberui.com/r/zoom-parallax.json或在 components.json 設定 registries 後,改用 @webberui/zoom-parallax 安裝。
安裝依賴後,從 registry JSON(/r/zoom-parallax.json 的 files[0].content)複製 zoom-parallax.tsx 原始碼到你的 components/ui/ 目錄:
npm install motion clsx tailwind-merge使用
import { ZoomParallax } from "@/components/ui/zoom-parallax";
<ZoomParallax
images={[
{ src: "/photos/01.jpg", alt: "山稜" },
{ src: "/photos/02.jpg", alt: "海灣" },
{ src: "/photos/03.jpg", alt: "森林" },
{ src: "/photos/04.jpg", alt: "日出" },
{ src: "/photos/05.jpg", alt: "城市" },
{ src: "/photos/06.jpg", alt: "湖泊" },
{ src: "/photos/07.jpg", alt: "峽谷" },
]}
>
<h2 className="text-2xl font-bold text-white">Zoom Parallax</h2>
</ZoomParallax>元件本身會撐出一段捲動軌道(預設 h-[300vh]),中間的舞台以 sticky 釘住整個視窗;向下捲動時所有圖片以舞台中心為原點放大,外圍圖片放大得更快,形成穿越飛入的視差。
巢狀捲動容器
若捲動發生在具 overflow 的容器內(而非視窗),把該容器 ref 傳給 container,並用 className/stageClassName 覆寫軌道與舞台高度:
const scrollerRef = React.useRef<HTMLDivElement>(null);
<div ref={scrollerRef} className="h-[320px] overflow-y-auto">
<ZoomParallax
images={images}
container={scrollerRef}
className="h-[960px]" // 捲動軌道 = 舞台高度的數倍
stageClassName="h-[320px]" // 舞台 = 容器可視高度
/>
</div>Props
| Prop | 型別 | 預設值 | 說明 |
|---|---|---|---|
images | (string | { src: string; alt?: string })[] | — | 圖片來源,建議 5–7 張 |
container | RefObject<HTMLElement | null> | — | 巢狀捲動容器的 ref;預設以視窗為捲動容器 |
layout | ZoomParallaxSlot[] | 內建 7 格 | 覆寫穿越版面;圖片多於版面時循環取用 |
smooth | boolean | true | 是否以 spring 平滑捲動進度 |
children | ReactNode | — | 疊在圖片上方、置中且不攔截指標的內容 |
aria-label | string | "縮放穿越圖組" | 圖組的無障礙名稱 |
className | string | h-[300vh] | 外層捲動軌道;高度決定可捲動距離 |
stageClassName | string | h-screen | 釘住的舞台;巢狀捲動時覆寫為容器高度 |
imageClassName | string | — | 套用到每張圖片元素 |
ZoomParallaxSlot
| 欄位 | 型別 | 說明 |
|---|---|---|
scale | number | 捲動到底時的目標放大倍率(起始恆為 1) |
width | number | 圖片寬度,佔舞台寬度的百分比 |
height | number | 圖片高度,佔舞台高度的百分比 |
x | number | 相對舞台中心的水平位移(百分比) |
y | number | 相對舞台中心的垂直位移(百分比) |
細節
- 版面尺寸與位移全部使用「佔舞台的百分比」,因此不論全螢幕或巢狀小容器都能自適應。
- 每張圖片各自綁定一條
useTransform,把捲動進度映射成獨立的縮放曲線;外圍圖片倍率越高、飛散越快。 - 縮放預設經過 spring 平滑(
smooth),滾輪停下時仍會順勢收斂,不會硬跳。 - 圖片依序對應
layout;圖片多於版面格數時會循環取用同一組位置。
可及性
- 使用者系統開啟「減少動態效果」時,改以靜態圖格(grid)呈現全部圖片,不做任何捲動放大。
- 舞台容器帶
role="group"與aria-label;未提供alt的裝飾性圖片會標記aria-hidden,有alt的圖片則正常朗讀。