小k08051005
3月4日 14:05
关注

  // 创建 ref 数组
  const sectionRefs = useRef<(HTMLElement | null)[]>([]);

  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach(entry => {
          if (entry.isIntersecting) {
            setActiveId(entry.target.id);
          }
        });
      },
      {
        root: null, // 使用视口作为根
        rootMargin: '0px',
        threshold: 0.5 // 当元素50%可见时触发
      }
    );

   

评论
收藏
更多
// 开始观察所有 section sectionRefs.current.forEach(ref => { if (ref) observer.observe(ref); }); return () => { sectionRefs.current.forEach(ref => { if (ref) observer.unobserve(ref); }); }; }, []);
0
0
// 创建 ref 数组 const sectionRefs = useRef<(HTMLElement | null)[]>([]); useEffect(() => { const observer = new IntersectionObserver( (entries) => { entries.forEach(entry => { if (entry.isIntersecting) { setActiveId(entry.target.id); } }); }, { root: null, // 使用视口作为根 rootMargin: '0px', threshold: 0.5 // 当元素50%可见时触发 } );
0
0
博君一肖~
0
0
博君一肖~
0
0
博君一肖~
0
0