Intersection Observer API:观察视口的中心

Nut*_*ari 10 javascript dom web intersection-observer

我试图观察视口中心的交点,我尝试在 rootMargin 中传递负值

rootMargin: '-45% 10% -45%'
Run Code Online (Sandbox Code Playgroud)

但它似乎不能正常工作。

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

wil*_*nco 28

rootMargin经过几次尝试后,Intersection Observer以及如何处理交叉点可能会变得有点混乱,因此我将尝试详细说明如何在特定场景中实现这种情况:

\n
    \n
  • 当元素的顶部或底部到达视口的垂直中心时检测元素的相交
  • \n
\n

元素顶部/底部在视口中心相交

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

通过这样做,elementHasIntersected一旦元素的最顶部或最底部边缘与视口的中心相交,回调就会被调用。

\n

相当容易,对吧?现在,如果您想实现类似的“中心交叉点”场景,例如:

\n
    \n
  • 当元素的垂直中心到达视口的垂直中心时检测元素的交集
  • \n
\n

然后,这将需要一种不同的方法,因为rootMargin: \'-50% 0% -50% 0%\'永远不会允许在 50%\xe2\x80\x93 处触发交集,因为元素永远不会 50% 可见。如果这个特定场景对您有价值,我很乐意集思广益,所以请告诉我。

\n

这是我发布的关于 Intersection Observer APIIntersection Observer Playground 的文章,您可以在其中尝试不同的配置(此版本有一些限制),也许您会找到您需要的组合。

\n