且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查元素是否滚动到顶部

更新时间:2023-10-28 22:11:04

您必须侦听滚动事件,然后根据当前滚动距离检查每个元素,如下所示:

  $(window).on('scroll',function(){
var scrollTop = $(this).scrollTop();

$('。background1,.background2')。each(function(){
var topDistance = $(this).offset()。top;

if(顶部距离+100)< scrollTop){
alert($(this).text()+'被滚动到顶部');
}
});
} );


I want to check if an element is scrolled to top with an offset of ~ 100px.

I´ve got a page with 5 subcontents and 2 classes to make backgrounds. It looks like this:

<div class="background1">
Content1
</div>
<div class="background2">
Content2
</div>
<div class="background1">
Content3
</div>
<div class="background2">
Content4
</div>
<div class="background1">
Content5
</div>

Now i want to check, when one of these classes reaches the top by scrolling

This is one of my last trys:

$('.background1', '.background2').position(function(){
             if($(this).position().top == 100){
            alert('checkThis');
        }
        }); 

I think this is my closest try by now...of course this code is in document.ready and at the end of my code....

TLDR: How to check if an element got scrolled to top (and some offset)?

You have to listen for the scroll event, then check each element against the currently scrolled distance, something like :

$(window).on('scroll', function() {
    var scrollTop = $(this).scrollTop();

    $('.background1, .background2').each(function() {
        var topDistance = $(this).offset().top;

        if ( (topDistance+100) < scrollTop ) {
            alert( $(this).text() + ' was scrolled to the top' );
        }
    });
});