检查 div 是否在窗口中可见?

13
6个回答

17

以下是您需要的所有变量...

var $myElt       = $('.myElement');      // whatever element you want to check
var $window      = $(window);            // the window jQuery element
var myTop        = $myElt.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) {
    // element is in the window
} else {
    // element is NOT in the window
    // maybe use this to scroll... 
    // $('html, body').animate({scrollTop: myTop}, 300);
}

jQuery 参考资料:


4

使用$('#element').offset().top;来检测元素顶部位置。

$(window).scrollTop();用于检测当前滚动位置。

然后,使用$(window).height();来检测当前窗口高度。

接下来,您只需要进行一些简单的数学计算即可。


1
function isScrolledIntoView(elem)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
}

源代码:滚动后检查元素是否可见


0

请查看以下的lazyload插件:

http://plugins.jquery.com/files/jquery.lazyload.js__6.txt

以“返回相对于当前视图的项目状态”的注释开头的部分检查元素是否在视口中可见。


0
如果您正在使用jQuery,只需尝试检查文档位置即可。
$('html').position().top;

例如:

$(document).bind("scroll", checkLink);

function checkLink(){

   /* Position will checked out after 1 sec when user finish scrolling  */
   var s = setTimeout(function(){ 

     var docHeight = $('html').position().top;
     var allLinks = $('.navigation a');

     if ( docHeight < 0 && docHeight <= -1000 ) { 

        allLinks.removeClass('active');
        $('a.firstlink').addClass('active');

     } else 
     if ( docHeight < -1000 && docHeight <= -2000 ) { 

        allLinks.removeClass('active');
        $('a.secondlink').addClass('active');

     } else { /* .... */ }

   $(document).bind("scroll", checkLink);
   }, 1000);

  $(document).unbind('scroll');
}

但是你们的例子中的人并没有长时间坚持这个 :) 他们只是在点击时切换类

$('#navigation').localScroll();
    $('#navigation li a').click( function () {
        $('#navigation li a').removeClass("active");
        $(this).addClass("active");
    }); 

0

2022的答案 - 你不再需要使用jQuery来实现这个功能了

现在可以使用IntersectionObserver和纯JavaScript来实现。

其他解决方案的问题在于它们会触发太多次。

例如,你可以这样做:

var observer = new IntersectionObserver(function(entries) {
    if(entries[0].isIntersecting === true) {
        console.log('Element is in the window');
    } else {
        console.log("Element is not in the window"); 
    }
});

observer.observe(document.querySelector(".myObject"));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接