JavaScript检查元素是否在顶视口之外

JavaScript check if element is outside top viewport

本文关键字:视口 检查 元素 是否 JavaScript      更新时间:2023-09-26

我有一个代码,它可以很好地检查元素是否在底部视口之外,如下所示:

function posY(elm) {
let test = elm, top = 0;
while(!!test && test.tagName.toLowerCase() !== "body") {
    top += test.offsetTop;
    test = test.offsetParent;
}
return top;
}
function viewPortHeight() {
let de = document.documentElement;
if(!window.innerWidth)
{ return window.innerHeight; }
else if( de && !isNaN(de.clientHeight) )
{ return de.clientHeight; }
return 0;
}
function scrollY() {
if( window.pageYOffset ) { return window.pageYOffset; }
return Math.max(document.documentElement.scrollTop, document.body.scrollTop);
}
function checkvisible (elm) {
let vpH = viewPortHeight(), // Viewport Height
    st = scrollY(), // Scroll Top
    y = posY(elm);
return (y > (vpH + st));
}
        if (hasActivity && isHidden) {
            isVisibleCSS = <div className='onscreen'>More activity below ↓</div>;
        } else if (hasActivity && !isHidden) {
            //technically, there's no need for this here, but since I'm paranoid, let's leave it here please.
        }

我的问题是,我如何调整这个代码,或者创建一个类似于这个代码的新代码,以识别元素何时在顶视口之外?

干杯。

对于一个完全离开视图顶部的元素,则是该元素的顶部偏移量和高度的总和,如下面的JS Fiddle

var $test = document.getElementById('test'),
  $tOffset = $test.offsetTop,
  $tHeight = $test.clientHeight,
  $winH = window.innerHeight,
  $scrollY;
window.addEventListener('scroll', function() {
  $scrollY = window.scrollY;
  if ($scrollY > ($tOffset + $tHeight)) {
    console.log('out of the top');
  }
});
body {
  margin: 0;
  padding: 0;
  padding-top: 200px;
  height: 1500px;
}
#test {
  width: 100px;
  height: 150px;
  background-color: orange;
  margin: 0 auto;
}
<div id="test"></div>