【问题标题】:How to play animation only when the element is on screen仅当元素在屏幕上时如何播放动画
【发布时间】:2021-01-03 16:44:06
【问题描述】:

我正在使用 React,我需要知道元素何时在屏幕上播放淡入淡出动画,并使其出现在屏幕上。因为动画总是在页面加载时播放,但是如果您必须滚动才能看到元素,那么您将永远看不到动画:(

<Grid container className="AnimationContainer">
  <img src="/images/animation1/circle.svg" className="Animation1-1" />
  <img src="/images/animation1/calculator.svg" className="Animation1-2" />
</Grid>

在我的 CSS 文件中,我有:

.AnimationContainer {
  place-content: center;
  height: 200px;
  width: 100%;
}
.Animation1-1 {
  animation: fading 2s;
}
.Animation1-2 {
  animation: fading 1.2s;
}
@keyframes fading{
  0%{opacity:0}
  100%{opacity:1}
}

只有在 Grid "AnimationContainer" 或 img "Animation1-1"/"Animation1-2" 可见时,我可以在此处执行什么操作?

【问题讨论】:

    标签: javascript css reactjs animation css-animations


    【解决方案1】:

    使用Intersection Observer 来检测元素何时可见,并且仅在可见时设置animation 属性。使用react-intersection-observer 很容易做到这一点:

    import { useInView } from "react-intersection-observer"
    
    const Example => () => {
      const [ref, inView] = useInView({ threshold: 0.5 })
    
      return (
        <Grid ref={ref} container className="AnimationContainer">
          <img src="/images/animation1/circle.svg" className={inView ? "Animation1-1" : null} />
          <img src="/images/animation1/calculator.svg" className={inView ? "Animation1-2" : null} />
        </Grid>
      )
    }
    

    【讨论】:

    • 您忘记在 Grid(或 img)标签上添加“ref={ref}”,但谢谢!它解决了问题!
    • @Octaviotastico 哎呀,你是对的。为后代修复它。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 2019-04-26
    • 1970-01-01
    • 1970-01-01
    • 2022-12-16
    • 1970-01-01
    • 2021-10-15
    相关资源
    最近更新 更多