【问题标题】:intersectionObserver callback called outside threshold在阈值之外调用intersectionObserver 回调
【发布时间】:2017-09-06 16:04:50
【问题描述】:

试图理解intersectionObserver API 中的一个怪癖

如果观察到的元素部分显示在屏幕上但未达到选项中定义的阈值,我希望回调不会触发,但它确实。试图了解为什么或如何在页面加载时阻止它。

function handleIntersect(entries, observer) {
  entries.forEach(function(entry) {
    if (entry.isIntersecting) {
      // Should only fire at >= 0.8
      console.log(entry, entry.intersectionRatio);
      entry.target.classList.add('play');
    }
  });
}

function createObserver(element) {
  let observer;

  const options = {
    threshold: [0.8]
  };

  observer = new IntersectionObserver(handleIntersect, options);
  observer.observe(element);
}

const waypoints = document.querySelectorAll('.section');

waypoints.forEach(waypoint => {
  createObserver(waypoint); 
});

简化的测试用例: https://codepen.io/WithAnEs/pen/gxZPMK

请注意前 2 部分是如何动画化的,即使第二部分不符合 0.8 阈值(控制台日志)。第一个倾向是添加intersectionRatio > 0.8 检查,但这是重复的工作。此外,比率报告延迟,因此可能不够准确,无法通过此检查。

【问题讨论】:

    标签: javascript intersection-observer


    【解决方案1】:

    isIntersecting 不依赖于阈值。它是true,如果target 元素接触或相交root 元素。所以如果intersectionRatio > 0,它总是true

    如果观察到的元素部分显示在屏幕上但尚未满足 选项中定义的阈值我希望回调不会 火,但确实如此。

    一般情况下,callback 会在条件 intersectionRatio >= your_threshold 发生变化时被调用。因此可以使用任何intersectionRatio 值调用它。

    此外,它总是在最初被调用。

    还要注意0.8 只是您想要的阈值,但observer.thresholds[0] 是实际的。无需详细说明,它们可能会有所不同,例如在 Chrome 中。

    【讨论】:

    • 不,我了解 isIntersecting 属性。我添加了 isIntersecting 检查以防止交叉点观察者的每个实例触发 st 页面加载。我遇到的问题是阻止初始页面加载触发超出预定义阈值的元素。我可以添加一个可见百分比检查,但考虑到阈值已定义,这似乎很奇怪。
    • 更新了答案
    • 请注意,Chrome 对isIntersecting 的实现与其他浏览器不同。它似乎不符合规范,这意味着它可能是falseintersectionRatio > 0。此处的错误:bugs.chromium.org/p/chromium/issues/detail?id=925643
    猜你喜欢
    • 1970-01-01
    • 2014-08-06
    • 1970-01-01
    • 2021-09-19
    • 1970-01-01
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 2014-05-13
    相关资源
    最近更新 更多