亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何僅當元素在屏幕上時才播放動畫

如何僅當元素在屏幕上時才播放動畫

POPMUISE 2023-03-10 15:07:45
我在 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}}當網格“AnimationContainer”或img “Animation1-1”/“Animation1-2”可見時,我可以在這里做什么才能播放它?
查看完整描述

1 回答

?
胡說叔叔

TA貢獻1804條經驗 獲得超8個贊

使用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>

  )

}


查看完整回答
反對 回復 2023-03-10
  • 1 回答
  • 0 關注
  • 115 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號