F13▸S004▸framer-motion
Parallax Image
視差背景
難度 ★★★★★標籤 視差 · useScroll · useTransform3 min read
效果簡述
捲動時背景移動速度比前景慢(或反向),製造空間深度。
用 useScroll({ target/container }) + useTransform 把 progress 映射
到 y 軸位移。
滾動我看視差
speed -20%
Claude Code Prompt
參考:S004 parallax image
技術:framer-motion useScroll + useTransform
具體行為:
- 容器 ref 綁在 section 上
- useScroll({ target: ref, offset: ['start end', 'end start'] })
- const y = useTransform(scrollYProgress, [0,1], ['-15%','15%'])
- <motion.div style={ y }>... 背景圖
限制:
- 視差幅度 ±10% ~ ±20%
- 不要對所有區塊都套(會暈)
- 移動裝置可以保留,差距小一點(±8%)完整程式碼
'use client'
import { motion, useScroll, useTransform } from 'framer-motion'
import { useRef } from 'react'
export function ParallaxImage() {
const ref = useRef<HTMLDivElement>(null)
const { scrollYProgress } = useScroll({
target: ref,
offset: ['start end', 'end start'],
})
const y = useTransform(scrollYProgress, [0, 1], ['-15%', '15%'])
return (
<section ref={ref} className="relative h-[500px] overflow-hidden">
<motion.div
style={{ y }}
className="absolute inset-0 bg-gradient-to-br from-orange-400/40 to-background"
/>
<div className="relative z-10 p-8">內容在這層</div>
</section>
)
}何時用
- ✅ Hero / KV 區塊
- ✅ 章節分隔處(給呼吸感)
- ✅ 案例展示的背景圖
何時別用
- ❌ 連續好幾個區塊都套(暈眩)
- ❌ 文字密集區(背景動會干擾閱讀)
- ❌ 包進 sticky / iframe 區域
我踩過的坑
-
offset 字串寫錯整個沒動:
['start end', 'end start']是 「進視口到離開視口」整個區間,不是[0, 1]。 -
背景沒包 overflow-hidden:視差位移會超出容器邊界,會看到 下方背景滲出來。
-
手機別關:很多人直接 mobile 改 0,但完全沒視差感更廉價。 降到 ±8% 比較剛好。
相關效果
- F11 Scroll Progress Bar — 同樣 useScroll
- F14 Sticky Section — 配合常見