動畫系統 v4.2
生產級 UI 動畫系統,適用於 React / Next.js。
專注於效能、無障礙性與易用性——而非裝飾。
使用時機
在以下情況使用此動畫系統:
- 引導注意力(如:引導流程、關鍵操作)
- 溝通狀態(載入中、成功、錯誤、過渡)
- 保持空間連續性(版面變更、導航)
適當情境
- 互動式元件(按鈕、模態框、選單)
- 狀態轉變(載入中 → 已載入、開啟 → 關閉)
- 導航與版面連續性(共享元素、交叉淡入淡出)
考慮事項
- 無障礙性:務必支援減少動畫
- 裝置適配:針對低階裝置進行調整
- 效能取捨:回應速度優先於視覺流暢度
應避免使用動畫的情況
- 純粹用於裝飾
- 降低易用性或清晰度
- 對效能造成負面影響
運作方式
核心原則
動畫必須:
- 引導注意力
- 溝通狀態
- 保持空間連續性
若以上皆非 → 移除它。
安裝
npm install motion
版本
motion/react- 預設,適用於目前的 Motion for React 專案(套件名:motion)framer-motion- 舊版匯入路徑,適用於仍依賴 Framer Motion 的專案
請勿混用。 混用會導致內部排程器衝突及 AnimatePresence 上下文損壞——來自不同套件的元件將無法協調退出動畫。
若要檢查專案使用的版本:
cat package.json | grep -E '"motion"|"framer-motion"'
請始終從單一來源一致地匯入:
// 正確(現代)
import { motion, AnimatePresence } from "motion/react"
// 正確(舊版)
import { motion, AnimatePresence } from "framer-motion"
// 同一個專案中絕不混用兩者
Motion 標記
// motionTokens.ts
export const motionTokens = {
duration: {
fast: 0.18,
normal: 0.35,
slow: 0.6
},
// 將這些用作 `transition` 物件中的 `ease` 值:
// transition={{ duration: motionTokens.duration.normal, ease: motionTokens.easing.smooth }}
easing: {
smooth: [0.22, 1, 0.36, 1] as [number, number, number, number],
sharp: [0.4, 0, 0.2, 1] as [number, number, number, number]
},
distance: {
sm: 8,
md: 16,
lg: 24
}
}
使用範例:
import { motionTokens } from "@/lib/motionTokens"
<motion.div
initial={{ opacity: 0, y: motionTokens.distance.md }}
animate={{ opacity: 1, y: 0 }}
transition={{
duration: motionTokens.duration.normal,
ease: motionTokens.easing.smooth
}}
/>
效能規則
安全
- transform
- opacity
避免
- width / height
- top / left
規則:回應速度 > 流暢度
裝置適配
此啟發式方法結合了 CPU 核心數和可用記憶體,以提供更可靠的信號。deviceMemory 可在 Chrome/Android 上使用;後備方案涵蓋 Safari 和 Firefox。
const isLowEnd =
typeof navigator !== "undefined" && (
// 低記憶體(僅 Chrome/Android;其他處為 undefined → 視為效能良好)
(navigator.deviceMemory !== undefined && navigator.deviceMemory <= 2) ||
// 核心數少 AND 無記憶體 API(涵蓋效能較弱的硬體上的 Safari/Firefox)
(navigator.deviceMemory === undefined && navigator.hardwareConcurrency <= 4)
)
const duration = isLowEnd ? 0.2 : 0.4
無障礙性
JS(useReducedMotion)
import { motion, useReducedMotion } from "motion/react"
export function FadeIn() {
const reduce = useReducedMotion()
return (
<motion.div
initial={{ opacity: 0, y: reduce ? 0 : 24 }}
animate={{ opacity: 1, y: 0 }}
/>
)
}
CSS
@media (prefers-reduced-motion: reduce) {
.motion-safe-transition {
transition: opacity 0.2s;
}
.motion-reduce-transform {
transform: none !important;
}
}
Tailwind
<div class="motion-safe:animate-fade motion-reduce:opacity-100"></div>
架構與模式
核心模式
| 情境 | 模式 |
|---|---|
| 懸停回饋 | whileHover |
| 點按/按壓回饋 | whileTap |
| 滾動時顯示 | whileInView |
| 與滾動連結的值 | useScroll + useTransform |
| 條件式掛載/卸載 | AnimatePresence |
| 小幅版面變動(單一元素,變化 < ~300px) | layout 屬性 |
| 大幅版面變動或全頁重新佈局 | 避免使用 layout;改用 CSS 過渡或頁面級路由 |
| 複雜、命令式的序列 | useAnimate |
為何要避免在大型容器上使用
layout? Framer 的版面動畫使用transform來協調位置,但在佔滿整個視窗或觸發深度重新佈局的元素上,測量成本會導致明顯的畫面卡頓和 CLS。建議優先使用 CSS Grid/Flexbox 過渡,或僅在特定子元素上配合layoutId使用。
版面與過渡
- 共享元素過渡 →
layoutId(每個已掛載的實例必須唯一) - 進入/退出過渡 →
AnimatePresence(參閱下方的mode指引)
AnimatePresence mode
請始終明確指定 mode——預設值 ("sync") 會同時執行進入和退出,這在大多數 UI 模式中會導致視覺重疊。
mode | 使用時機 |
|---|---|
"wait" | 退出完成後再開始進入。用於模態框、提示訊息、頁面過渡。 |
"sync"(預設) | 進入和退出重疊。僅在重疊是故意設計時使用(例如:交叉淡入淡出的輪播)。 |
"popLayout" | 退出的元素立即從流程中彈出;其餘項目動畫填充空間。用於清單、頁籤、可關閉的卡片。 |
// 模態框 — 始終使用 "wait"
<AnimatePresence mode="wait">
{open && <Modal key="modal" />}
</AnimatePresence>
// 可關閉的清單項目 — 使用 "popLayout"
<AnimatePresence mode="popLayout">
{items.map(item => <Card key={item.id} />)}
</AnimatePresence>
進階模式(概念)
- 視差(與滾動連結的變形)
- 滾動敘事(固定區段)
- 3D 傾斜(基於指標的變形)
- 交叉淡入淡出(共享
layoutId) - 漸進顯示(clip-path)
- 骨架載入(循環透明度)
- 微互動(懸停/點按回饋)
- 彈簧系統(基於物理的動畫)
模態框必備
- 焦點陷阱
- Escape 關閉
- 滾動鎖定
- ARIA 角色
- 使用
AnimatePresence mode="wait"確保退出動畫在下一個模態框進入前完成
完整範例
import React, { useEffect, useRef, useState } from "react"
import { motion, AnimatePresence } from "motion/react"
function useFocusTrap(ref: React.RefObject<HTMLDivElement | null>, active: boolean) {
useEffect(() => {
if (!active || !ref.current) return
const el = ref.current
const focusable = el.querySelectorAll<HTMLElement>(
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
)
const first = focusable[0]
const last = focusable[focusable.length - 1]
function handleKey(e: KeyboardEvent) {
if (e.key !== "Tab") return
if (e.shiftKey && document.activeElement === first) {
e.preventDefault()
last?.focus()
} else if (!e.shiftKey && document.activeElement === last) {
e.preventDefault()
first?.focus()
}
}
el.addEventListener("keydown", handleKey)
first?.focus()
return () => el.removeEventListener("keydown", handleKey)
}, [active, ref])
}
function useScrollLock(active: boolean) {
useEffect(() => {
if (!active) return
const prev = document.body.style.overflow
document.body.style.overflow = "hidden"
return () => { document.body.style.overflow = prev }
}, [active])
}
function Modal({ open, closeModal }: { open: boolean; closeModal: () => void }) {
const ref = useRef<HTMLDivElement>(null)
useFocusTrap(ref, open)
useScrollLock(open)
useEffect(() => {
function onKey(e: KeyboardEvent) {
if (e.key === "Escape") closeModal()
}
if (open) window.addEventListener("keydown", onKey)
return () => window.removeEventListener("keydown", onKey)
}, [open, closeModal])
return (
// mode="wait" 確保退出動畫在新的模態框進入前完成
<AnimatePresence mode="wait">
{open && (
<motion.div
role="dialog"
aria-modal="true"
aria-labelledby="modal-title"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.2 }}
className="fixed inset-0 flex items-center justify-center bg-black/40"
>
<motion.div
ref={ref}
initial={{ scale: 0.95, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
exit={{ scale: 0.95, opacity: 0 }}
transition={{ duration: 0.2, ease: [0.22, 1, 0.36, 1] }}
className="bg-white p-6 rounded"
>
<h2 id="modal-title">Dialog Title</h2>
<button onClick={closeModal}>Close</button>
</motion.div>
</motion.div>
)}
</AnimatePresence>
)
}
export function Example() {
const [open, setOpen] = useState(false)
return (
<>
<button onClick={() => setOpen(true)}>Open</button>
<Modal open={open} closeModal={() => setOpen(false)} />
</>
)
}
SSR 安全
- 在伺服器端和用戶端渲染之間配對初始狀態
- 避免隱含的動畫起始點(務必明確設定
initial) - 在 Next.js App Router 中,將動畫元件包裹在
"use client"內
除錯
檢查:
- 錯誤的匯入(混用
motion/react和framer-motion) - Next.js App Router 中缺少
"use client"指令 AnimatePresence子元件缺少key屬性- 水合不符(伺服器端渲染與用戶端初始狀態不同)
- 在大型容器上誤用
layout屬性導致重新佈局卡頓 - 由狀態驅動的動畫未觸發(檢查相依陣列)
品質保證
- 無 CLS
- 鍵盤操作正常
- 模態框中焦點被鎖定
- ARIA 角色正確(
role="dialog"、aria-modal="true") - 尊重減少動畫設定(
useReducedMotion+ CSS media query) - Next.js 中無水合警告
- 動畫在卸載時能乾淨停止(無記憶體洩漏)
- 在所有使用位置上明確設定
AnimatePresence mode
反模式
- 動畫化版面屬性(
width、height、top、left) - 無目的的無限動畫(始終反問:這傳遞了什麼狀態?)
- 過度交錯清單(保持
staggerChildren≤ 0.1s;超過會感覺緩慢) - 忽略減少動畫偏好設定
- 在大型或全視窗容器上使用
layout - 省略
AnimatePresence的mode(預設"sync"會導致視覺重疊) - 純粹為裝飾而使用動畫
哲學
動畫就是互動設計。
最終法則
如果動畫並未提升使用者體驗 → 移除它。
範例
按鈕互動
import { motion } from "motion/react"
export function Button() {
return (
<motion.button
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.97 }}
transition={{ duration: 0.15, ease: [0.4, 0, 0.2, 1] }}
>
Click me
</motion.button>
)
}
減少動畫範例
import { motion, useReducedMotion } from "motion/react"
export function FadeIn() {
const reduce = useReducedMotion()
return (
<motion.div
initial={{ opacity: 0, y: reduce ? 0 : 24 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: reduce ? 0.1 : 0.35, ease: [0.22, 1, 0.36, 1] }}
/>
)
}
交錯清單
import { motion } from "motion/react"
const container = {
hidden: {},
visible: {
transition: { staggerChildren: 0.08 } // 保持 ≤ 0.1s 以避免遲緩感
}
}
const item = {
hidden: { opacity: 0, y: 10 },
visible: { opacity: 1, y: 0, transition: { duration: 0.3, ease: [0.22, 1, 0.36, 1] } }
}
export function List() {
return (
<motion.ul variants={container} initial="hidden" animate="visible">
{[1, 2, 3].map(i => (
<motion.li key={i} variants={item}>Item {i}</motion.li>
))}
</motion.ul>
)
}
使用 AnimatePresence 的模態框
import { motion, AnimatePresence } from "motion/react"
export function Modal({ open }: { open: boolean }) {
return (
<AnimatePresence mode="wait">
{open && (
<motion.div
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.95 }}
transition={{ duration: 0.2, ease: [0.22, 1, 0.36, 1] }}
/>
)}
</AnimatePresence>
)
}
滾動視差
import { useScroll, useTransform, motion } from "motion/react"
export function Parallax() {
const { scrollYProgress } = useScroll()
const y = useTransform(scrollYProgress, [0, 1], [0, -80])
return <motion.div style={{ y }} />
}
骨架載入
import { motion } from "motion/react"
export function Skeleton() {
return (
<motion.div
className="bg-gray-200 h-6 w-full rounded"
animate={{ opacity: [0.5, 1, 0.5] }}
transition={{
duration: 1.5, // 舒適的脈衝——之前缺失,導致快速閃爍
repeat: Infinity,
ease: "easeInOut"
}}
/>
)
}
共享版面(交叉淡入淡出)
import { motion } from "motion/react"
// layoutId 在每個已掛載的實例中必須唯一。
// 如果可能存在多個實例,請附加唯一 id:
// layoutId={`shared-${item.id}`}
export function Shared() {
return <motion.div layoutId="shared" />
}