【问题标题】:Framer motion animate when element is in-view (When you scroll to element)当元素在视图中时 Framer 运动动画(当您滚动到元素时)
【发布时间】:2019-11-20 16:22:13
【问题描述】:

是否有任何内置方法可以在元素处于视图中时(例如,当我们滚动到元素时)开始动画?

Framer Motion 有安装动画部分,上面写着:

当一个组件挂载时,如果它们与 style 或 initial 中定义的值不同,它将自动动画到 animate 中的值

所以我真的找不到一种直接的方法来让动画在它出现时开始播放。

但是,我目前看到的唯一选项是使用Animation Controls,这意味着我必须手动在滚动上实现一个侦听器并触发control.start(),非常感谢任何更简单的方法。

【问题讨论】:

    标签: javascript reactjs animation framer-motion


    【解决方案1】:

    framer-motion 自 5.3 版起内置支持此用例。

    这是一个演示该模式的 CodeSandbox:https://codesandbox.io/s/framer-motion-animate-in-view-5-3-94j13

    相关代码:

    function FadeInWhenVisible({ children }) {
      return (
        <motion.div
          initial="hidden"
          whileInView="visible"
          viewport={{ once: true }}
          transition={{ duration: 0.3 }}
          variants={{
            visible: { opacity: 1, scale: 1 },
            hidden: { opacity: 0, scale: 0 }
          }}
        >
          {children}
        </motion.div>
      );
    }
    

    用法:

    <FadeInWhenVisible>
      <Box />
    </FadeInWhenVisible>
    

    以前的版本:

    您目前可以使用imperative animation controls 来实现此效果。交叉点观察器有助于检测元素当前是否可见。

    这是一个演示该模式的 CodeSandbox:https://codesandbox.io/s/framer-motion-animate-in-view-gqcc8

    相关代码:

    function FadeInWhenVisible({ children }) {
      const controls = useAnimation();
      const [ref, inView] = useInView();
    
      useEffect(() => {
        if (inView) {
          controls.start("visible");
        }
      }, [controls, inView]);
    
      return (
        <motion.div
          ref={ref}
          animate={controls}
          initial="hidden"
          transition={{ duration: 0.3 }}
          variants={{
            visible: { opacity: 1, scale: 1 },
            hidden: { opacity: 0, scale: 0 }
          }}
        >
          {children}
        </motion.div>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-20
      • 2011-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-03
      • 1970-01-01
      • 2021-05-06
      相关资源
      最近更新 更多