jQuery 检查元素是否滚动到顶部
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18961151/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
check if element got scrolled to top
提问by Top Questions
I want to check if an element is scrolled to top with an offset of ~ 100px.
我想检查一个元素是否以 ~ 100px 的偏移量滚动到顶部。
I′ve got a page with 5 subcontents and 2 classes to make backgrounds. It looks like this:
我有一个包含 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>
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....
我认为这是我现在最接近的尝试……当然,这段代码在 document.ready 中,并在我的代码末尾……
TLDR: How to check if an element got scrolled to top (and some offset)?
TLDR:如何检查元素是否滚动到顶部(以及一些偏移量)?
回答by adeneo
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' );
}
});
});