You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Framer Motion中实现无重叠的顺序动画?

在Framer Motion中实现无重叠的顺序动画

Framer Motion提供了几种内置的简洁方式来处理顺序动画,完全不需要手动计算delay,以下是最实用的两种方案:

方案一:使用useAnimation钩子 + Async/Await

利用useAnimation返回的控制器的start方法会返回Promise的特性,通过async/await可以轻松实现顺序执行,前一个动画完成后自动启动下一个:

import { motion, useAnimation } from "framer-motion";
import { useEffect } from "react";

function SequentialAnimation() {
  const controls = useAnimation();

  useEffect(() => {
    const runSequence = async () => {
      // 1. 执行淡入动画
      await controls.start({ 
        opacity: 1, 
        transition: { duration: 1 } 
      });
      // 2. 淡入完成后执行放大动画
      await controls.start({ 
        scale: 1.5, 
        transition: { duration: 1 } 
      });
      // 3. 放大完成后再次执行淡入(先淡出再淡入,还原初始视觉逻辑)
      await controls.start({ 
        opacity: 0, 
        transition: { duration: 1 } 
      });
      await controls.start({ 
        opacity: 1, 
        transition: { duration: 1 } 
      });
      
      // 需要循环执行整个序列时,递归调用即可
      runSequence();
    };

    runSequence();
  }, [controls]);

  return (
    <motion.div
      initial={{ opacity: 0, scale: 1 }}
      animate={controls}
      style={{ width: 100, height: 100, backgroundColor: "#2563eb" }}
    />
  );
}

export default SequentialAnimation;

方案二:使用sequence专用函数

Framer Motion内置了sequence函数,专门用于按顺序执行多个动画任务,每个任务完成后才会启动下一个,代码结构更清晰:

import { motion, useAnimation, sequence } from "framer-motion";
import { useEffect } from "react";

function SequentialAnimation() {
  const controls = useAnimation();

  useEffect(() => {
    // 定义动画序列任务
    const animationTasks = sequence([
      () => controls.start({ opacity: 1, transition: { duration: 1 } }),
      () => controls.start({ scale: 1.5, transition: { duration: 1 } }),
      () => controls.start({ opacity: 0, transition: { duration: 1 } }),
      () => controls.start({ opacity: 1, transition: { duration: 1 } }),
    ]);

    // 循环执行序列
    const loopSequence = async () => {
      while (true) {
        await animationTasks();
      }
    };

    loopSequence();
  }, [controls]);

  return (
    <motion.div
      initial={{ opacity: 0, scale: 1 }}
      animate={controls}
      style={{ width: 100, height: 100, backgroundColor: "#2563eb" }}
    />
  );
}

export default SequentialAnimation;

核心优势

这两种方案都完全依赖动画的完成事件(而非手动设置延迟),确保动画100%无重叠,而且可以随时调整单个动画的时长,不需要同步修改其他动画的delay值,维护成本极低。

内容的提问来源于stack exchange,提问作者Benassila Reda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 16:40:06