【问题标题】:Intersection Observer API: Observe the center of the viewportIntersection Observer API:观察视口的中心
【发布时间】:2019-02-21 12:51:44
【问题描述】:

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

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

但它似乎无法正常工作。

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

【问题讨论】:

  • 你的例子很好。您可以让rootMargin: -50% 0 创建将触发的中心线。

标签: javascript web dom intersection-observer


【解决方案1】:

Intersection Observer 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% 可见。如果对您有价值,我很乐意就这个特定场景集思广益,所以请告诉我。

这里有一个article I posted about the Intersection Observer APIThe Intersection Observer Playground 我放在一起,你可以尝试不同的配置(这个版本有一些限制),也许你会找到你需要的组合。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多