我创建了一个动画,需要几秒钟的时间播放。动画应该只在元素在视图中时运行,所以我使用了whileInView
。这是正确的,但是当我向下滚动时(因此元素不在视图中),动画似乎向后运行,因为当我再次向上滚动时,我可以看到动画不是从开始开始,而是从它向后运行时到达的点开始,当元素再次进入视图时。我希望动画从头开始运行。
我创建了一个小沙箱来演示这个问题:
https://codesandbox.io/s/dreamy-cache-mk2dq2?file=/src/App.js
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 }}
transition={{ duration: 5, ease: "linear" }}
>
<p>
The box should be moving now. Scroll down and then up again. The
animation will not instantly reset but run backwards.
</p>
</motion.div>
</div>
);
}
字符串
当你打开沙盒时,蓝色的盒子会移动。动画需要5秒。向下滚动,然后再向上滚动(在5秒内)。动画将从某个点开始运行,而不是从开始运行。
如何使动画在元素进入视图时从头开始运行?
2条答案
按热度按时间fgw7neuy1#
useInView
来跟踪div何时滚动过去,并在发生变化时调用useEffect
。useInView referenceuseAnimate
而不是div定义see more about useAnimate here。字符串
wtlkbnrh2#
p7dxb的回答给了我一个想法。我找到了一个非常简单的解决办法。您只需为
initial
和whileInView
设置不同的过渡值。对initial
使用0秒的持续时间:字符串
下面是新的沙盒:https://codesandbox.io/s/objective-elgamal-p49wdq