【问题标题】:How to get first visible body element (on screen) with pure javascript如何使用纯 javascript 获取第一个可见的 body 元素(在屏幕上)
【发布时间】:2019-09-18 12:02:19
【问题描述】:

有人知道如何引用当前可见屏幕上“最接近顶部”的 dom 元素吗?

类似这样的解决方案: How to get first visible DOM element currently showing on the screen? ;但纯粹是在 javascript 上。

不要关心位置坐标,也不要关心其他任何事情,而只是获取它的参考。

提前致谢

【问题讨论】:

  • 链接的问题使用了 JavaScript,“纯 JavaScript”是什么意思?
  • 可能意味着没有 jQuery
  • 这是需要经常计算的东西吗(例如在滚动时)?如果是这样,您可能会发现 IntersectionObserver 很有用。
  • @amn 我的意思是,不涉及任何库(例如 jQuery
  • @spender 仪式。这就是为什么我指出“当前可见屏幕上的元素”。谢谢你的留言!!

标签: javascript dom


【解决方案1】:

这与this answer 基本相同,但没有jQuery。

function visible(elem) {
  return !(elem.clientHeight === 0 || elem.clientWidth === 0)
}

let first;
let firstOffY;
let allVisible = Array.from(document.querySelectorAll('body > *')).filter(visible)
for(const elem of allVisible) {
  //Calculaate the offset to the document 
  //See: https://stackoverflow.com/a/18673641/7448536
  const offY = elem.getBoundingClientRect().top + document.documentElement.scrollTop
  if (first == null || offY < firstOffY) {
    first = elem;
    firstOffY = offY;
  }
}

first.classList.add('highlight');
.highlight {
  background-color: yellow;
}
<div>
  <p>Some Text</p>
  <h1>Headline</h1>
</div>
  • document.querySelectorAll('body &gt; *')选择body下的所有元素
  • Array.fromquerySelectorAll 的返回值转换为实数数组
  • .filter(visible)丢弃所有不可见的元素

【讨论】:

    【解决方案2】:

    如果你需要更好的兼容性,这里稍微调整一下文德林的回答。

    function visible(elem) {
      return !(elem.clientHeight === 0 || elem.clientWidth === 0)
    }
    
    let first;
    let firstOffY;
    var elems = [], source = document.querySelectorAll('body > *');
    for(var elemI=0;elemI<source.length;elemI++) {
       elems.push(source[elemI]);
    }
    let allVisible = elems.filter(visible)
    for(var elem in allVisible) {
      elem = allVisible[elem];
      //Calculaate the offset to the document 
      //See: https://stackoverflow.com/a/18673641/7448536
      const offY = elem.getBoundingClientRect().top + document.documentElement.scrollTop
      if (first == null || offY < firstOffY) {
        first = elem;
        firstOffY = offY;
      }
    } 
    
    console.log(first.outerHTML);
    first.classList.add('highlight');
    .highlight {
      background-color: yellow;
    }
    <div>
      <p>Some Text</p>
      <h1>Headline</h1>
    </div>

    【讨论】:

    • 真的很感激!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-24
    • 2013-10-30
    • 2012-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多