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

时间:2015-11-26 09:19:45

标签: javascript viewport

我有一个代码可以正常工作以检查元素是否在底部视口之外,如下所示:

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.
        }

我的问题是,如何修改此代码或创建一个类似于此代码的新代码,以识别元素何时位于顶部视口之外?

干杯。

1 个答案:

答案 0 :(得分:1)

要使一个元素完全脱离视图顶部,那么元素的顶部偏移量和它的高度之和就像在JS Fiddle

中一样

&#13;
&#13;
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');
  }
});
&#13;
body {
  margin: 0;
  padding: 0;
  padding-top: 200px;
  height: 1500px;
}
#test {
  width: 100px;
  height: 150px;
  background-color: orange;
  margin: 0 auto;
}
&#13;
<div id="test"></div>
&#13;
&#13;
&#13;