检查元素的一部分是否在视口中

Jop*_*Jop 3 javascript viewport

我正在编写一个 Javascript 代码来检查元素是否在视口中。但现在我有一个代码,仅当元素 100% 在视口中时才返回 true。有没有办法,例如,如果有 10 个像素返回 true,或者如果元素的百分比...在视口中返回 true?

到目前为止我的代码

<script type="text/javascript">
    var elem = document.getElementById("result");
    var bounding = elem.getBoundingClientRect();
        if (bounding.top >= 0 && bounding.left >= 0 && bounding.right <= window.innerWidth && bounding.bottom <= window.innerHeight) {
            alert('in viewport');  
        }
</script>
Run Code Online (Sandbox Code Playgroud)

Zac*_*ber 12

基于 @Jorg 的代码,这与Intersection Observer API相同,这是一种检查交叉点的新方法。根据Can I Use,这适用于所有现代浏览器 ~ 93.5%

设置此值是为了将视口内 50% 的任何内容视为在阈值内。我把它设置得这么大,这样就很容易看出它是如何工作的。

您会注意到,回调仅在阈值处调用(在初始检查之后)。因此,如果您想要准确的交叉百分比,您可能需要增加检查的阈值数量。

let callback = (entries, observer) => {
  entries.forEach(entry => {
    entry.target.style.backgroundColor = entry.isIntersecting ? 'green' : 'red';
    entry.target.innerHTML = entry.intersectionRatio;
  })
}
let observer = new IntersectionObserver(callback, {
  threshold: [0.5] // If 50% of the element is in the screen, we count it!
  // Can change the thresholds based on your needs. The default is 0 - it'll run only when the element first comes into view
});



['div1', 'div2', 'div3', 'div4'].forEach(d => {
  const div = document.getElementById(d);
  if (div) observer.observe(div);
})
Run Code Online (Sandbox Code Playgroud)
html,
body {
  padding: 0;
  margin: 0;
}

body {
  height: 200vh;
  width: 200vw;
}

#div1 {
  position: absolute;
  left: calc(100vw - 60px - 10px);
  top: 10px;
  height: 100px;
  width: 60px;
  background-color: red;
  color: white;
}

#div2 {
  position: absolute;
  left: 20px;
  top: 10px;
  height: 50px;
  width: 60px;
  background-color: blue;
  color: white;
}

#div3 {
  position: absolute;
  left: calc(100vw - 260px + 50px);
  top: max(calc(100vh - 350px + 120px), 120px);
  height: 350px;
  width: 260px;
  background-color: green;
  color: white;
  text-align: left;
}

#div4 {
  position: absolute;
  height: 9000px;
  width: 9000px;
  color: black;
  background-color: yellow;
}
Run Code Online (Sandbox Code Playgroud)
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>

<!-- enable this div to see an example of a div LARGER than your viewport.  -->
<!-- <div id="div4"></div> -->
Run Code Online (Sandbox Code Playgroud)