javascript - 如何检测元素可见性(z-index、固定、不透明度等)(Intersection Observer V2 替代方案)

标签 javascript z-index visibility intersection-observer

Intersection Observer V2 将引入新功能,以根据不透明度、z-index 和固定定位等因素检测实际可见度。

信息:https://developers.google.com/web/updates/2019/02/intersectionobserver-v2

问题:是否有替代方法或 polyfill 来检测当前浏览器中的实际可见性?

测试:https://jsfiddle.net/v3kgewhf/

// Intersection Observer V2
const observer = new IntersectionObserver((changes) => {
  for (const change of changes) {
    // ⚠️ Feature detection
    if (typeof change.isVisible === 'undefined') {
      // The browser doesn't support Intersection Observer v2, falling back to v1 behavior.
      change.isVisible = true;
    }
    if (change.isIntersecting && change.isVisible) {
      visibleSince = change.time;
    } else {
      visibleSince = 0;
    }
  }
}, {
  threshold: [1.0],
  // 🆕 Track the actual visibility of the element
  trackVisibility: true,
  // 🆕 Set a minimum delay between notifications
  delay: 100
}));```

最佳答案

另一种方法是轮询您希望使用 DocumentOrShadowRoot.elementFromPoint 检测可见性的点。具有 setInterval 延迟的方法,类似于您将用作 Intersection Observer v2 的延迟的方法。
这是此时两者之间的caniuse链接elementFromPoint支持 99% 以上的用户 vs Intersection Observer v2仅支持 69%+。

关于javascript - 如何检测元素可见性(z-index、固定、不透明度等)(Intersection Observer V2 替代方案),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56875801/

相关文章:

javascript - 验证表单 - 出现多个错误消息

javascript - iframe 触摸事件 preventDefault

html - ie6上z-index的问题

css - z-index 何时/如何打破堆叠上下文?

java - setVisible(boolean) 的问题

android - 如果绑定(bind)适配器提供 getter,请检查适配器是否正确注释以及参数类型是否匹配

javascript - 当用户离开页面时提示用户保存

javascript - 使用 Chrome 存储 API 存储简单对象时遇到问题

javascript - 幻灯片放映中的 Zindex 图像

android - 我的应用程序的键盘永久可见