import { useRef, useEffect } from 'react';
export default function Box() {
const ref = useRef(null);
useEffect(() => {
const div = ref.current;
const observer = new IntersectionObserver(entries => {
const entry = entries[0];
if (entry.isIntersecting) {
document.body.style.backgroundColor = 'black';
document.body.style.color = 'white';
} else {
document.body.style.backgroundColor = 'white';
document.body.style.color = 'black';
}
}, {
threshold: 1.0
});
observer.observe(div);
return () => {
observer.disconnect();
}
}, []);
return (
<div ref={ref} style={{
margin: 20,
height: 100,
width: 100,
border: '2px solid black',
backgroundColor: 'blue'
}} />
);
}
交叉观察器 API (在官网看到的一个api 感觉有点用)
本文介绍了如何在React组件中使用IntersectionObserverAPI实现元素进入视口时改变网页背景和文字颜色,展示了其在Web开发中的具体用法和与MDNWeb文档的关系。
摘要由CSDN通过智能技术生成