检查元素是否滚动到顶部。

15

我想检查一个元素是否向上滚动,并带有大约100像素的偏移量。

我有一个包含5个子内容和2个类以制作背景的页面。它看起来像这样:

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

现在我想检查,当其中一个类通过滚动到达顶部时

这是我的最后一次尝试之一:

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

我认为这是目前为止最接近的尝试...当然,此代码在 document.ready 中,并且在我的代码结尾处执行....

简而言之:如何检查元素是否滚动到顶部(以及某些偏移量)?


1
窗口的滚动事件似乎是您正在寻找的。 - A. Wolff
1个回答

29

你需要监听滚动事件,然后检查每个元素与当前滚动的距离是否匹配,类似于:

$(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' );
        }
    });
});

这正是我所搜索的内容...我完全固定在如何获取位置上了...但忘记了滚动到那里...谢谢!8分钟内接受。 - Top Questions
2
position() 获取元素相对于父级的位置,我猜你在寻找 offset(),它获取相对于文档的位置。此外,请注意选择器,因为您的选择器查找 .background2 内的 .background1,并且不会同时选择两个。 - adeneo
太棒了!这一行代码:var scrollTop = $(this).scrollTop();正是我一直在寻找的。我之前一直想不通为什么 .offset().top 的值根本没有变化。现在我明白了,因为偏移值是相对于文档的,所以它是永久性的——这就是为什么你需要将其与 $(window).scrollTop() 值进行比较的原因。 - rgb_life

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