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

如何让元素每次进入视图时从头执行framer-motion动画?

解决Framer Motion中whileInView动画每次进入视图从头启动的问题

要实现元素每次进入视图时动画从头开始执行,你可以采用以下两种可行方案:


方案1:配置whileInView的重置与过渡行为

给motion.div添加reset: true属性,并关闭反向过渡动画,让元素离开视图时立即重置到初始状态,而非反向播放:

import "./styles.css";
import { motion } from "framer-motion";

export default function App() {
  return (
    <div style={{ height: "1000px" }}>
      <motion.div
        id="box"
        initial={{ x: 0 }}
        whileInView={{ x: 300 }}
        reset={true}
        transition={{ 
          duration: 5, 
          ease: "linear",
          reverse: false
        }}
      >
        <p>
          The box should be moving now. Scroll down and then up again. The
          animation will start from the beginning every time it enters the view.
        </p>
      </motion.div>
    </div>
  );
}

方案2:手动监听视图状态控制动画

使用useInView钩子实时监测元素是否在视图内,配合animate属性手动触发或重置动画,逻辑更灵活:

import "./styles.css";
import { motion, useInView } from "framer-motion";
import { useRef } from "react";

export default function App() {
  const ref = useRef(null);
  const isInView = useInView(ref, { once: false });

  return (
    <div style={{ height: "1000px" }}>
      <motion.div
        ref={ref}
        id="box"
        initial={{ x: 0 }}
        animate={isInView ? { x: 300 } : { x: 0 }}
        transition={{ duration: 5, ease: "linear" }}
      >
        <p>
          The box should be moving now. Scroll down and then up again. The
          animation will start from the beginning every time it enters the view.
        </p>
      </motion.div>
    </div>
  );
}

方案说明

  • 方案1中,reset: true确保元素离开视图时回到初始状态,reverse: false禁用了默认的反向过渡动画,让元素离开时立刻重置,下次进入视图时从头播放正向动画。
  • 方案2通过useInView精准控制动画触发时机:元素进入视图时执行正向动画,离开时立即回到初始位置,完全由开发者掌控动画逻辑。

内容的提问来源于stack exchange,提问作者Michel Krämer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 01:03:42