POPMUISE
2023-03-10 15:07:45
我在 React 工作,我需要知道元素何時(shí)在屏幕上播放淡入淡出動畫,并使其出現(xiàn)在屏幕上。因?yàn)閯赢嬁偸窃陧撁婕虞d時(shí)播放,但如果你必須滾動才能看到元素,那么你將永遠(yuǎ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}}當(dāng)網(wǎng)格“AnimationContainer”或img “Animation1-1”/“Animation1-2”可見時(shí),我可以在這里做什么才能播放它?
1 回答
胡說叔叔
TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超8個贊
使用Intersection Observer檢測元素何時(shí)可見,并且僅animation在可見時(shí)設(shè)置屬性。使用react-intersection-observer很容易做到這一點(diǎn):
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>
)
}
添加回答
舉報(bào)
0/150
提交
取消
