交叉点观察者API:观察视口的中心



我正在尝试观察视口中心的交叉点,我尝试在rootmargin中传递负值

rootMargin: '-45% 10% -45%'

,但似乎无法正常工作。

我的要求是观察我的元素到达屏幕中心时的交叉点。

交集观察者rootMargin以及在几次尝试之后如何处理交叉点可能会变得有些混乱,因此我将尝试详细说明如何在特定方案中实现这一点:

  • 当元素的顶部或底部到达视口的垂直中心

在视口

的相交元素的顶部/底部
const intersectionAtTopOrBottomElement = document.querySelector('.top-bottom-element');
const elementHasIntersected = (entries, o) => {...};
const ioConfiguration = {
  /**
   * This rootMargin creates a horizontal line vertically centered
   * that will help trigger an intersection at that the very point.
   */
  rootMargin: '-50% 0% -50% 0%',
  /**
   * This is the default so you could remove it.
   * I just wanted to leave it here to make it more explicit
   * as this threshold is the only one that works with the above
   * rootMargin
   */
  threshold: 0
};
const observer = new IntersectionObserver(elementHasIntersected, ioConfiguration);
observer.observe(intersectionAtTopOrBottomElement);

通过执行此操作,elementHasIntersected回调将在该元素最高或最底部边缘与视口的中心相交后立即被调用。

相当容易,对吗?现在,如果您想获得类似的"中心交叉点"。场景,例如:

  • 其垂直中心到达视口的垂直中心
  • 时,检测元素的交集

那么,这将需要一种不同的方法,因为rootMargin: '-50% 0% -50% 0%'永远不会以50%的速度触发交叉路口 - 因为元素永远不会可见50%。如果这对您很有价值,我会很乐意集思广益,所以请告诉我。

这是我发表的有关交叉点观察者API和交叉点观察者游乐场的文章,我可以在其中尝试不同的配置(此版本有一些限制),也许您会找到所需的组合。

<</p>

最新更新