使用jQuery检测元素何时靠近页面底部

时间:2013-05-15 16:06:02

标签: javascript jquery

我有一个脚本可以解决页面顶部元素列表的距离,但我不确定如何检测它与底部的距离。当它击中底部(好吧,在底部之前20px)我想发射一个事件并淡出它:

$(window).on('load resize scroll', function () {
    $('.links__item').each(function () {
        if (($(this).offset().top - $(window).scrollTop()) < 20) {
            $(this).stop().fadeTo(100, 0)
        } else {
            $(this).stop().fadeTo('fast', 1)
        }
    })
})

如果有人有任何建议,非常感谢。我正在遍历各个元素以检测它,所以当其中一个从底部击中20px时,我想淡出它。谢谢!

2 个答案:

答案 0 :(得分:15)

您可以在计算中使用jQuery函数height(),例如:

$(window).height();
$(this).height();

具体来说,如果你想检测元素的顶部是否接近页面的底部,你可以使用这个计算:

if ( $(this).offset().top > ($(window).scrollTop() + $(window).height() - 20) ) // True

答案 1 :(得分:4)

太平,

我不确定你要发射什么,但你可以像这样测试页面的底部

$(window).on('load resize scroll', function () {
    $('.links__item').each(function () {
        if( ($(this).offset().top > ($(window).scrollTop() + $(window).height() - 20)) {
            $(this).stop().fadeTo(100, 0)
        } else {
            $(this).stop().fadeTo('fast', 1)
        }
    })
})

原因是jQuery根据其高度找到页面的底部

1 $(window).height();   // returns height of browser viewport
2 $(document).height(); // returns height of HTML document