POPMUISE
2023-03-10 15:07:45
我在 React 工作,我需要知道元素何時在屏幕上播放淡入淡出動畫,并使其出現(xiàn)在屏幕上。因為動畫總是在頁面加載時播放,但如果你必須滾動才能看到元素,那么你將永遠看不到動畫:(<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}}當網(wǎng)格“AnimationContainer”或img “Animation1-1”/“Animation1-2”可見時,我可以在這里做什么才能播放它?
1 回答

胡說叔叔
TA貢獻1804條經(jīng)驗 獲得超8個贊
使用Intersection Observer檢測元素何時可見,并且僅animation
在可見時設(shè)置屬性。使用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>
)
}
添加回答
舉報
0/150
提交
取消