关于 motion-framer
motion-framer 是一项围绕 Motion 和 Framer Motion 的开发 Skill,面向使用 React 或 JavaScript 构建动画界面的开发者。内容涵盖手势、布局与退出动画、弹簧效果、钩子和实用示例。
主要功能
- 01使用 motion 组件声明动画
- 02支持悬停、点击和拖拽手势
- 03制作布局变化与退出动画
- 04提供弹簧物理和滚动动画
- 05介绍动画控制钩子与变体
适用场景
- 01为按钮和菜单添加交互效果
- 02制作页面切换与滚动动画
- 03实现拖放和布局重排
- 04构建带状态变化的动画界面
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ freshtechbro/ claudedesignskills --skill motion-framer安装后在 Claude Code 中输入/motion-framer确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
assets/examples/README.mdassets/starter_motion/index.htmlpackage.jsonREADME.mdvite.config.jsassets/starter_motion/src/App.cssApp.jsxmain.jsxassets/starter_motion/src/components/DraggableBox.jsxHoverCard.jsxStaggerList.jsxreferences/api_reference.mdscripts/animation_generator.pyvariant_builder.py详细介绍
Motion 与 Framer Motion
概述
Motion(前身为 Framer Motion)是一个可用于生产环境的 React 和 JavaScript 动画库,只需少量代码即可实现声明式、高性能的动画。它提供了为 HTML 元素赋予动画能力的 motion 组件,支持手势识别(悬停、轻触、拖拽、聚焦),还包含布局动画、退出动画和弹簧物理等高级功能。
适用场景:
- 构建交互式 UI 组件(按钮、卡片、菜单)
- 创建微交互和悬停效果
- 实现页面切换和路由动画
- 添加基于滚动的动画和视差效果
- 为布局变化添加动画(调整大小、重新排序、共享元素切换)
- 构建拖放界面
- 创建复杂的动画序列和基于状态的动画
- 用功能更强大、可控性更高的动画替代 CSS 过渡效果
技术:
- Motion(v11+)- 由 Framer Motion 创建者打造的现代精简库
- Framer Motion - 功能齐全的前身(仍被广泛使用)
- 兼容 React 18+,也支持 Vue
- 支持 TypeScript
- 适用于 Next.js、Vite、Remix 及所有现代 React 框架
核心概念
1. Motion 组件
在 HTML/SVG 元素前加上 motion.,即可将其转换为可制作动画的组件:
import { motion } from "framer-motion"
// Regular HTML becomes motion component
<motion.div />
<motion.button />
<motion.svg />
<motion.path />
每个 motion 组件都接受 animate、initial、transition 等动画属性,以及 whileHover、whileTap 等手势属性。
2. Animate 属性
animate 属性定义动画的目标状态。值发生变化时,Motion 会自动将动画过渡到目标状态:
// Simple animation - x position changes
<motion.div animate={{ x: 100 }} />
// Multiple properties
<motion.div animate={{ x: 100, opacity: 1, scale: 1.2 }} />
// Animates when state changes
const [isOpen, setIsOpen] = useState(false)
<motion.div animate={{ width: isOpen ? 300 : 100 }} />
3. 初始状态
使用 initial 属性设置动画开始前的初始状态:
<motion.div
initial={{ opacity: 0, y: 50 }}
animate={{ opacity: 1, y: 0 }}
/>
设置 initial={false} 可禁用挂载时的初始动画。
4. 过渡效果
使用 transition 属性控制动画在不同状态之间的过渡方式:
// Duration-based
<motion.div
animate={{ x: 100 }}
transition={{ duration: 0.5, ease: "easeInOut" }}
/>
// Spring physics
<motion.div
animate={{ scale: 1.2 }}
transition={{ type: "spring", stiffness: 300, damping: 20 }}
/>
// Different transitions for different properties
<motion.div
animate={{ x: 100, opacity: 1 }}
transition={{
x: { type: "spring", stiffness: 300 },
opacity: { duration: 0.2 }
}}
/>
过渡类型:
"tween"(默认)- 基于时长并带有缓动效果"spring"- 基于物理效果的弹簧动画"inertia"- 减速动画(用于拖拽)
5. 变体
使用命名变体组织动画状态,让代码更简洁,并将动画状态传递给子元素:
const variants = {
hidden: { opacity: 0, y: 20 },
visible: { opacity: 1, y: 0 },
exit: { opacity: 0, scale: 0.9 }
}
<motion.div
variants={variants}
initial="hidden"
animate="visible"
exit="exit"
/>
变体传递 - 子元素会自动继承父元素的变体状态:
const containerVariants = {
hidden: { opacity: 0 },
visible: {
opacity: 1,
transition: {
staggerChildren: 0.1 // Stagger child animations
}
}
}
const itemVariants = {
hidden: { x: -20, opacity: 0 },
visible: { x: 0, opacity: 1 }
}
<motion.ul variants={containerVariants} initial="hidden" animate="visible">
<motion.li variants={itemVariants} />
<motion.li variants={itemVariants} />
<motion.li variants={itemVariants} />
</motion.ul>
常见模式
1. 悬停动画
使用 whileHover 属性创建悬停动画:
// Simple hover effect
<motion.button
whileHover={{ scale: 1.1 }}
transition={{ duration: 0.2 }}
>
Hover me
</motion.button>
// Multiple properties
<motion.div
whileHover={{
scale: 1.05,
backgroundColor: "#f0f0f0",
boxShadow: "0px 10px 30px rgba(0, 0, 0, 0.2)"
}}
>
Hover card
</motion.div>
// With custom transition
<motion.button
whileHover={{
scale: 1.2,
transition: { duration: 0.1 } // Transition for gesture start
}}
transition={{ duration: 0.5 }} // Transition for gesture end
>
Button
</motion.button>
包含嵌套元素的悬停效果:
<motion.div whileHover="hover" variants={cardVariants}>
<motion.h3 variants={titleVariants}>Title</motion.h3>
<motion.img variants={imageVariants} />
</motion.div>
2. 轻触/按压动画
使用 whileTap 属性创建轻触/按压动画:
// Scale down on tap
<motion.button
whileTap={{ scale: 0.9 }}
>
Click me
</motion.button>
// Combined hover + tap
<motion.button
whileHover={{ scale: 1.1 }}
whileTap={{ scale: 0.95, rotate: 3 }}
>
Interactive button
</motion.button>
// With variants
const buttonVariants = {
rest: { scale: 1 },
hover: { scale: 1.1 },
pressed: { scale: 0.95 }
}
<motion.button
variants={buttonVariants}
initial="rest"
whileHover="hover"
whileTap="pressed"
>
Button
</motion.button>
3. 拖拽交互
使用 drag 属性使元素可拖拽:
// Basic dragging (both axes)
<motion.div drag />
// Constrain to axis
<motion.div drag="x" /> // Only horizontal
<motion.div drag="y" /> // Only vertical
// Drag constraints
<motion.div
drag
dragConstraints={{ left: -100, right: 100, top: -100, bottom: 100 }}
/>
// Drag with parent constraints
<motion.div ref={constraintsRef}>
<motion.div drag dragConstraints={constraintsRef} />
</motion.div>
// Visual feedback while dragging
<motion.div
drag
whileDrag={{
scale: 1.1,
boxShadow: "0px 10px 20px rgba(0,0,0,0.2)",
cursor: "grabbing"
}}
dragElastic={0.1} // Elasticity when dragging outside constraints
dragTransition={{ bounceStiffness: 600, bounceDamping: 20 }}
/>
拖拽事件:
<motion.div
drag
onDragStart={(event, info) => console.log(info.point)}
onDrag={(event, info) => console.log(info.offset)}
onDragEnd={(event, info) => console.log(info.velocity)}
/>
4. 退出动画(AnimatePresence)
使用 AnimatePresence 为从 DOM 中移除的组件添加动画:
import { AnimatePresence } from "framer-motion"
// Basic exit animation
<AnimatePresence>
{isVisible && (
<motion.div
key="modal"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
/>
)}
</AnimatePresence>
关键要求:
- 组件必须是
<AnimatePresence>的直接子元素 - 必须设置唯一的
key属性 - 使用
exit属性定义退出动画
带退出动画的列表项:
<AnimatePresence>
{items.map(item => (
<motion.li
key={item.id}
initial={{ opacity: 0, x: -50 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: 50 }}
layout // Smooth layout shifts
>
{item.name}
</motion.li>
))}
</AnimatePresence>
交错退出动画:
const containerVariants = {
hidden: { opacity: 0 },
visible: {
opacity: 1,
transition: {
when: "beforeChildren",
staggerChildren: 0.1
}
},
exit: {
opacity: 0,
transition: {
when: "afterChildren",
staggerChildren: 0.05,
staggerDirection: -1 // Reverse order
}
}
}
<AnimatePresence>
{show && (
<motion.div variants={containerVariants} initial="hidden" animate="visible" exit="exit">
<motion.div variants={itemVariants} />
<motion.div variants={itemVariants} />
<motion.div variants={itemVariants} />
</motion.div>
)}
</AnimatePresence>
5. 布局动画
使用 layout 属性自动为布局变化(位置、尺寸)添加动画:
// Animate all layout changes
<motion.div layout />
// Animate only position changes
<motion.div layout="position" />
// Animate only size changes
<motion.div layout="size" />
网格布局动画:
const [columns, setColumns] = useState(3)
<motion.div className="grid">
{items.map(item => (
<motion.div
key={item.id}
layout
transition={{ layout: { duration: 0.3, ease: "easeInOut" } }}
/>
))}
</motion.div>
共享布局动画(layoutId):
使用 layoutId 连接两个不同的元素,实现平滑过渡:
// Tab indicator example
<nav>
{tabs.map(tab => (
<button key={tab.id} onClick={() => setActive(tab.id)}>
{tab.label}
{activeTab === tab.id && (
<motion.div
layoutId="underline"
style={{ position: 'absolute', bottom: 0, left: 0, right: 0, height: 2 }}
/>
)}
</button>
))}
</nav>
// Modal opening from thumbnail
<motion.img
src={thumbnail}
layoutId="product-image"
onClick={() => setExpanded(true)}
/>
<AnimatePresence>
{expanded && (
<motion.div layoutId="product-image">
<img src={fullsize} />
</motion.div>
)}
</AnimatePresence>
6. 基于滚动的动画
使用 whileInView 在元素进入视口时为其添加动画:
<motion.div
initial={{ opacity: 0, y: 50 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true, amount: 0.8 }} // once: trigger once, amount: 80% visible
transition={{ duration: 0.5 }}
>
Animates when scrolled into view
</motion.div>
视口选项:
once: true- 动画仅触发一次amount: 0.5- 元素可见部分的比例(0-1),或"some"|"all"margin: "-100px"- 调整视口边界
交错滚动动画:
<motion.ul
initial="hidden"
whileInView="visible"
viewport={{ once: true, amount: 0.3 }}
variants={{
visible: {
opacity: 1,
transition: { staggerChildren: 0.1 }
},
hidden: { opacity: 0 }
}}
>
<motion.li variants={itemVariants} />
<motion.li variants={itemVariants} />
<motion.li variants={itemVariants} />
</motion.ul>
7. 弹簧动画
使用弹簧物理效果创建自然、有弹性的动画:
// Basic spring
<motion.div
animate={{ scale: 1.2 }}
transition={{ type: "spring" }}
/>
// Customize spring physics
<motion.div
animate={{ x: 100 }}
transition={{
type: "spring",
stiffness: 300, // Higher = faster, snappier (default: 100)
damping: 20, // Higher = less bouncy (default: 10)
mass: 1, // Higher = more inertia (default: 1)
}}
/>
// Visual duration (easier spring control)
<motion.div
animate={{ rotate: 90 }}
transition={{
type: "spring",
visualDuration: 0.5, // Perceived duration
bounce: 0.25 // Bounciness (0-1, default: 0.25)
}}
/>
弹簧预设:
- 柔和:
stiffness: 100, damping: 20 - 摇摆:
stiffness: 200, damping: 10 - 刚硬:
stiffness: 400, damping: 30 - 缓慢:
stiffness: 50, damping: 20
手势识别
Motion 提供声明式的手势处理器:
手势属性
<motion.div
whileHover={{ scale: 1.1 }} // Pointer hovers over element
whileTap={{ scale: 0.9 }} // Primary pointer presses element
whileFocus={{ outline: "2px" }} // Element gains focus
whileDrag={{ scale: 1.1 }} // Element is being dragged
whileInView={{ opacity: 1 }} // Element is in viewport
/>
手势事件
<motion.div
onHoverStart={(event, info) => {}}
onHoverEnd={(event, info) => {}}
onTap={(event, info) => {}}
onTapStart={(event, info) => {}}
onTapCancel={(event, info) => {}}
onDragStart={(event, info) => {}}
onDrag={(event, info) => {}}
onDragEnd={(event, info) => {}}
onViewportEnter={(entry) => {}}
onViewportLeave={(entry) => {}}
/>
事件信息对象包含:
point: { x, y }- 页面坐标offset: { x, y }- 相对于拖动起点的偏移量velocity: { x, y }- 拖动速度
Hooks
useAnimate
使用 useAnimate hook 手动控制动画:
import { useAnimate } from "framer-motion"
function Component() {
const [scope, animate] = useAnimate()
useEffect(() => {
// Animate multiple elements
animate([
[scope.current, { opacity: 1 }],
["li", { x: 0, opacity: 1 }, { delay: stagger(0.1) }],
[".button", { scale: 1.2 }]
])
}, [])
return (
<div ref={scope}>
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
<button className="button">Click</button>
</div>
)
}
动画控制:
const controls = animate(element, { x: 100 })
controls.play()
controls.pause()
controls.stop()
controls.speed = 0.5
controls.time = 0 // Seek to start
useSpring
创建弹簧动画的运动值:
import { useSpring } from "framer-motion"
function Component() {
const x = useSpring(0, { stiffness: 300, damping: 20 })
return (
<motion.div style={{ x }}>
<button onClick={() => x.set(100)}>Move</button>
</motion.div>
)
}
useInView
检测元素是否位于视口中:
import { useInView } from "framer-motion"
function Component() {
const ref = useRef(null)
const isInView = useInView(ref, { once: true, amount: 0.5 })
return (
<div ref={ref}>
{isInView ? "In view!" : "Not in view"}
</div>
)
}
集成模式
与 GSAP 集成
将 Motion 用于基于状态的动画,将 GSAP 用于复杂时间轴:
import { motion } from "framer-motion"
import gsap from "gsap"
function Component() {
const boxRef = useRef()
const handleClick = () => {
// Use GSAP for complex timeline
const tl = gsap.timeline()
tl.to(boxRef.current, { rotation: 360, duration: 1 })
.to(boxRef.current, { scale: 1.5, duration: 0.5 })
}
return (
// Use Motion for hover/tap/layout animations
<motion.div
ref={boxRef}
whileHover={{ scale: 1.1 }}
onClick={handleClick}
/>
)
}
与 React Three Fiber 集成
使用 Motion 值为 3D 对象添加动画:
import { motion } from "framer-motion"
import { useFrame } from "@react-three/fiber"
function Box() {
const x = useMotionValue(0)
useFrame(() => {
// Sync Motion value with Three.js position
meshRef.current.position.x = x.get()
})
return (
<>
<mesh ref={meshRef}>
<boxGeometry />
<meshStandardMaterial />
</mesh>
<motion.div
style={{ x }}
drag="x"
dragConstraints={{ left: -5, right: 5 }}
/>
</>
)
}
与表单库集成
为表单验证状态添加动画:
import { motion, AnimatePresence } from "framer-motion"
function FormField({ error }) {
return (
<div>
<motion.input
animate={{
borderColor: error ? "#ff0000" : "#cccccc",
x: error ? [0, -10, 10, -10, 10, 0] : 0 // Shake animation
}}
transition={{ duration: 0.4 }}
/>
<AnimatePresence>
{error && (
<motion.p
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -10 }}
style={{ color: "#ff0000" }}
>
{error}
</motion.p>
)}
</AnimatePresence>
</div>
)
}
性能优化
1. 使用变换属性
变换属性(x、y、scale、rotate)由硬件加速:
// ✅ Good - Hardware accelerated
<motion.div animate={{ x: 100, scale: 1.2 }} />
// ❌ Avoid - Triggers layout/paint
<motion.div animate={{ left: 100, width: 200 }} />
2. 单独的变换属性
Motion 支持单独的变换属性,让代码更简洁:
// Individual properties (Motion feature)
<motion.div style={{ x: 100, rotate: 45, scale: 1.2 }} />
// Traditional (also supported)
<motion.div style={{ transform: "translateX(100px) rotate(45deg) scale(1.2)" }} />
3. 为无障碍功能减少动画
尊重用户对减少动画的偏好:
import { useReducedMotion } from "framer-motion"
function Component() {
const shouldReduceMotion = useReducedMotion()
return (
<motion.div
animate={{ x: 100 }}
transition={shouldReduceMotion ? { duration: 0 } : { duration: 0.5 }}
/>
)
}
4. 布局动画的性能
布局动画可能开销较大。可通过以下方式优化:
// Specify what to animate
<motion.div layout="position" /> // Only position, not size
// Optimize transition
<motion.div
layout
transition={{
layout: { duration: 0.3, ease: "easeOut" }
}}
/>
5. 谨慎使用 layoutId
layoutId 会创建共享布局动画,但会全局跟踪元素。仅在需要时使用。
常见问题
1. 忘记使用 AnimatePresence 实现退出动画
问题: 退出动画不起作用
// ❌ Wrong - No AnimatePresence
{show && <motion.div exit={{ opacity: 0 }} />}
// ✅ Correct - Wrapped in AnimatePresence
<AnimatePresence>
{show && <motion.div exit={{ opacity: 0 }} />}
</AnimatePresence>
2. 列表中缺少 key 属性
问题: AnimatePresence 无法跟踪元素
// ❌ Wrong - No key
<AnimatePresence>
{items.map(item => <motion.div exit={{ opacity: 0 }} />)}
</AnimatePresence>
// ✅ Correct - Unique keys
<AnimatePresence>
{items.map(item => (
<motion.div key={item.id} exit={{ opacity: 0 }} />
))}
</AnimatePresence>
3. 为非变换属性添加动画
问题: 动画卡顿,性能不佳
// ❌ Avoid - Not hardware accelerated
<motion.div animate={{ top: 100, left: 50, width: 200 }} />
// ✅ Better - Use transforms
<motion.div animate={{ x: 50, y: 100, scaleX: 2 }} />
4. 过度使用布局动画
问题: 大量使用布局动画的元素会导致性能问题
// ❌ Too many layout animations
{items.map(item => <motion.div layout>{item}</motion.div>)}
// ✅ Use layout only where needed, optimize others
{items.map(item => (
<motion.div
key={item.id}
animate={{ opacity: 1 }} // Cheaper animation
exit={{ opacity: 0 }}
/>
))}
5. 复杂动画未使用 Variants
问题: 动画代码重复,无法编排子元素
// ❌ Repetitive
<motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} />
<motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} />
// ✅ Use variants
const variants = {
hidden: { opacity: 0 },
visible: { opacity: 1 }
}
<motion.div variants={variants} initial="hidden" animate="visible" />
<motion.div variants={variants} initial="hidden" animate="visible" />
6. 过渡时序不正确
问题: 过渡未应用于指定手势
// ❌ Wrong - General transition won't apply to whileHover
<motion.div
whileHover={{ scale: 1.2 }}
transition={{ duration: 1 }} // This applies to animate prop, not whileHover
/>
// ✅ Correct - Transition in whileHover or separate gesture transition
<motion.div
whileHover={{
scale: 1.2,
transition: { duration: 0.2 } // Applies to hover start
}}
transition={{ duration: 0.5 }} // Applies to hover end
/>
资源
官方文档
- Motion 文档 - Motion 官方文档
- Framer Motion 文档 - Framer Motion(旧版)
- Motion GitHub - 源代码和示例
捆绑资源
此技能包含:
references/
api_reference.md- 完整的 Motion API 参考variants_patterns.md- Variant 模式和编排gesture_guide.md- 全面的手势处理指南
scripts/
animation_generator.py- 生成 Motion 组件样板代码variant_builder.py- 交互式 Variant 配置工具
assets/
starter_motion/- 完整的 Motion + Vite 入门模板examples/- 真实场景中的 Motion 组件模式
社区资源
- Motion Dev Discord - 官方社区
- Framer Motion 示例 - 交互式示例
- Motion Recipes - 常见模式
- CodeSandbox 模板 - 在线演示