IntersectionObserver 新建一个对象 - options 选项 ( 父元素) observer 对象监控 observeRef 对象 使用 IntersectionObserver 好处是不会频繁触发 bindScroll 函数 -- 可以节省比较多资源
const options = {
root: containerRef, // 父容器 可 scroll
rootMargin: "0px",
threshold: 0.8, // 多少可视区
};
const observer = new IntersectionObserver(bindScroll, options);
// 监控元素
observer.observe(observeRef?.current);
const bindScroll = useCallback(
(entries, observer) => {
entries?.forEach(entry => {
// 每个条目描述一个目标元素观测点的交叉变化:
// entry.boundingClientRect
// entry.intersectionRatio
// entry.intersectionRect
// entry.isIntersecting
// entry.rootBounds
// entry.target
// entry.time
console.log(entry.boundingClientRect);
console.log("entry.isIntersecting 是否可视区:", entry.isIntersecting);
});
},
[],
);