在视口中滚动子元素

问题描述 投票:0回答:1
javascript scroll parent-child event-listener intersection-observer
1个回答
0
投票

尝试结合使用 Intersection Observer 和事件监听器。

可以设置Intersection Observer来观察高度较高的路段, 当它在视口中完全可见时,触发一个函数。

const section = document.querySelector('section');

const observer = new IntersectionObserver((entries) => {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      // Call a function to handle scrolling behavior
      handleSectionScroll();
    }
  });
});

observer.observe(section);

在handleSectionScroll函数中,可以给body添加滚动事件监听器来控制滚动行为。

const handleSectionScroll = () => {
  document.body.addEventListener('wheel', scrollBody);

  const scrollBody = (event) => {
    const sectionHeight = section.getBoundingClientRect().height;
    const bodyHeight = document.body.getBoundingClientRect().height;
    const scrollPosition = window.pageYOffset;

    if (scrollPosition < section.offsetTop) {
      // Scroll normally
      return;
    }

    if (scrollPosition >= section.offsetTop && scrollPosition < 
       section.offsetTop + sectionHeight - bodyHeight) {
       // Scroll the section
       section.scrollBy(0, event.deltaY);
       event.preventDefault();
    } else {
      // Scroll normally
      return;
    }
  }
}

尝试此代码并让我知道结果。

© www.soinside.com 2019 - 2024. All rights reserved.