Framer motion animate when element is in-view (When you scroll to element)

元气小坏坏 提交于 2020-05-16 02:41:08

问题


Is there any built-in way to make the animation start when the element is in-view (for example, when we scroll to the element)?

Framer Motion has mount animations section which says:

When a component mounts, it'll automatically animate to the values in animate if they're different from those defined in style or initial

So I couldn't really find a straight forward way to make the animation start when it comes into view.

However, I reached the only option I see for now is using Animation Controls which means I'll have to implement a listener on the scroll manually and trigger the control.start(), any easier ways are much appreciated.


回答1:


I'm afraid there is currently no built in way to achieve this. However as you mentioned, you can currently use the imperative animation controls to achieve this effect. Intersection observers are useful to detect if an element is currently visible.

Here's a CodeSandbox demonstrating the pattern: https://codesandbox.io/s/framer-motion-animate-in-view-gqcc8.

Relevant code:

function Box() {
  const controls = useAnimation();
  const [ref, inView] = useInView();

  useEffect(() => {
    if (inView) {
      controls.start("visible");
    }
  }, [controls, inView]);

  return (
    <motion.div
      ref={ref}
      animate={controls}
      initial="hidden"
      variants={{
        visible: { opacity: 1},
        hidden: { opacity: 0}
      }}
    />
  );
}


来源:https://stackoverflow.com/questions/58958972/framer-motion-animate-when-element-is-in-view-when-you-scroll-to-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!