gpt4 book ai didi

javascript - 交叉口观察者 API : Observe the center of the viewport

转载 作者:行者123 更新时间:2023-12-04 11:04:11 25 4
gpt4 key购买 nike

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

rootMargin: '-45% 10% -45%'
但它似乎不能正常工作。
我的要求是当我的元素到达屏幕中心时观察交叉点。

最佳答案

Intersection Observer rootMargin 以及如何处理交叉点在几次尝试后可能会变得有点困惑,所以我将尝试详细说明如何在特定场景下实现这一点:

  • 检测一个元素的交集,当它的顶部或底部 到达视口(viewport)的垂直中心

  • 在视口(viewport)中心与元素的顶部/底部相交
    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只要元素的最顶部或最底部边缘与视口(viewport)中心相交,回调就会被调用。
    相当容易吧?现在,如果您想实现类似的“中心路口”场景,例如:
  • 时检测元素的交集其垂直中心 到达视口(viewport)的垂直中心

  • 然后,这将需要与 rootMargin: '-50% 0% -50% 0%' 不同的方法。永远不会允许在 50% 时触发交叉点——因为元素永远不会 50% 可见。如果它对您有值(value),我很乐意就这个特定场景集思广益,所以请告诉我。
    这是 article I posted about the Intersection Observer APIThe Intersection Observer Playground我把你可以尝试不同配置的地方放在一起(这个版本有一些限制),也许你会找到你需要的组合。

    关于javascript - 交叉口观察者 API : Observe the center of the viewport,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54807535/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com