检查元素是否滚动到顶部 [英] check if element got scrolled to top

查看:113
本文介绍了检查元素是否滚动到顶部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查一个元素是否滚动到顶部,偏移量为〜100px。



我有一个包含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',' ($(this)).position()。top == 100){
alert('checkThis');
}
});

我认为这是我现在最接近的尝试......当然这个代码是在document.ready并在我的代码的结尾....

TLDR:如何检查一个元素是否滚动到顶部(和一些偏移量)?

解决方案

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

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

这篇关于检查元素是否滚动到顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆