Javascript,检查元素是否已离开屏幕

Javascript, check if element has left the screen

本文关键字:离开 屏幕 是否 元素 检查 Javascript      更新时间:2023-09-26

我正在尝试测试<div>是否已滚动出视图。

这就是我目前所拥有的,

$(window).on('scroll',function(){
    var divBottom    = $('#home').offset().bottom; 
    var windowTop    = $(window).scrollTop();           
    var windowBottom = windowTop + $(window).height();  
    if (divBottom >= windowTop) {
        console.log("yes");
    } else {
        console.log("no");
    }
});

无论我在哪里滚动,都不会记录任何内容。

我试图测试的是div的底部是否已经超过了窗口的顶部。

这里有一个非常有用的Vanilla JS函数。

var divposition = document.getElementById('home').getBoundingClientRect();
if( divposition.left+divposition.width < 0) {
    // element is off to the left of the view
}
if( divposition.top+divposition.height < 0) {
    // element is off the top of the view
}
if( divposition.top > window.innerHeight) {
    // element is off the bottom of the view
}
if( divposition.left > window.innerWidth) {
    // element is off to the right of the view
}

希望这能有所帮助!

divBottom就是undefined。您可以使用元素的top偏移量,然后通过将其高度添加到顶部来计算其底部值,就像在这个fiddle中一样。

$(window).on('scroll',function(){
    var $home = $('#home');
    var divBottom     = $home.offset().top + $home.height(); 
    var windowTop    = $(window).scrollTop();           
    console.log(divBottom, windowTop);
    if (divBottom >= windowTop) {
        console.log("yes");
    } else {
        console.log("no");
    }
});

试试这个。

var myTop        = $('#home').offset().top;  // the top y location of your element
var windowTop    = $(window).scrollTop();           // the top of the window
var windowBottom = windowTop + $(window).height();  // the bottom of the window

然后

if (myTop > windowTop && myTop < windowBottom) {

尝试:

$(window).scroll(function(){ 
//your code 
});