如何检查节点在交集中是否可见

时间:2018-10-03 11:06:43

标签: javascript html dom viewport intersection-observer

给予IntersectionObserver像这样:

const observeVisibility = intersectionMargin => {
    const observer = new IntersectionObserver(
        nodes => {
            if (nodes[0].isIntersecting) {
                /* is really in viewport? */
                this.observer.disconnect();
            }
        },
        { rootMargin: intersectionMargin }
    );

    observer.observe(...);
};

如何检查节点本身实际上是在视口中还是仅仅是导致观察者被调用的intersectionMargin?

1 个答案:

答案 0 :(得分:0)

IntersectionObserver将在加载时触发immediately。之后,当IntersectionObserver发生更改或isIntersecting越过您配置的intersectionRatio之一时,将调用传递到threshold的回调。

如您所见,回调获取条目列表,然后由您决定要执行什么操作。

//assuming 'threshold' is defined in scope

nodes => {
  nodes.forEach(entry => {
    const { isIntersecting, intersectionRatio } = entry;

    if (Array.isArray(threshold)) {
      threshold = threshold[threshold.length - 1];
   }

    if (isIntersecting || intersectionRatio >= threshold) {
      this.observer.disconnect();
    }
  }
}