【问题标题】:check if element got scrolled to top检查元素是否滚动到顶部
【发布时间】:2013-09-28 11:04:38
【问题描述】:

我想检查一个元素是否以大约 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 中,并且在我的代码末尾......

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

【问题讨论】:

  • window onscroll 事件似乎是你要找的

标签: jquery html scroll scrollto


【解决方案1】:

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

$(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 分钟后接受。
  • position() 获取元素相对于父元素的位置,我打赌你正在寻找offset(),它获取相对于文档的位置。还要注意选择器,因为您的选择器会在 .background2 中查找 .background1,并且不会同时选择两者。
  • 太棒了!这一行:var scrollTop = $(this).scrollTop(); 正是我想要的。我无法弄清楚为什么 .offset().top 值根本没有改变。现在我看到偏移值与文档相关,所以它是永久的——这就是为什么你需要将它与$(window).scrollTop() 值进行比较。
猜你喜欢
  • 1970-01-01
  • 2012-10-24
  • 2013-07-19
  • 2011-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多