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

如何在Framer Motion中实现上层元素移除后下层元素平滑位移动画

解决方案

要实现紫色div移除时粉色div的平滑位移动画,核心是让元素移除的过程被动画系统捕获,不能直接从DOM中删除元素。可以借助framer-motion的AnimatePresence组件处理元素的移除动画,配合延迟移除逻辑,让粉色div的位置变化触发Layout动画。

具体实现步骤

  • 引入AnimatePresence组件:它能检测子元素的挂载/卸载状态,为卸载过程添加过渡动画。
  • 给紫色div设置卸载动画:通过exit属性定义它移除前的收缩效果,让粉色div的位置变化被Layout动画捕捉。
  • 用AnimatePresence包裹动态渲染的紫色div:确保组件能感知到它的卸载动作。
  • 保留粉色div的layout属性:维持它在位置变化时的平滑过渡特性。

修改后的代码示例

import { motion, AnimatePresence } from "framer-motion";
import { useState } from "react";
import "./styles.css";

export default function App() {
  const [showPurple, setShowPurple] = useState(true);

  return (
    <div className="App">
      <button onClick={() => setShowPurple(!showPurple)}>切换紫色div</button>
      <AnimatePresence>
        {showPurple && (
          <motion.div
            className="purple"
            exit={{ height: 0, opacity: 0, margin: 0 }}
            transition={{ duration: 0.3 }}
          />
        )}
      </AnimatePresence>
      <motion.div className="pink" layout transition={{ duration: 0.3 }} />
    </div>
  );
}

原理说明

  • AnimatePresence会监听子元素的卸载动作,当showPurple变为false时,紫色div不会立刻被删除,而是先执行exit定义的动画(高度收缩至0、透明度消失)。
  • 在紫色div收缩的过程中,粉色div的位置会逐步上移,此时它的layout属性会捕捉到这个位置变化,自动生成平滑的位移动画。
  • 等紫色div的卸载动画完成后,它才会被真正从DOM中移除,整个过渡过程连贯自然。

内容的提问来源于stack exchange,提问作者shivam chandra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 20:39:06