使用jQuery检测元素是否接近页面底部

14

我有一个脚本,可以计算出一组元素距离页面顶部的距离,但我不确定如何检测它距离页面底部的距离。当它接近底部(实际上是在距离底部20像素处)时,我想要触发一个事件并将其淡出:

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

如果有人有任何建议,非常感谢。我正在循环遍历元素来检测它,因此当其中一个距离底部20像素时,我想使其渐隐。谢谢!


这可能会有帮助:https://dev59.com/62865IYBdhLWcg3wR8ah#3898152。 - palaѕн
2个回答

15

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

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

具体来说,如果您想检测元素顶部是否靠近页面底部,可以使用以下计算公式:

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

4

Halcyon,你好

我不确定你想要解决什么问题,但你可以像这样测试页面底部:

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

Bruno用相同的答案更快地到达了那里,但无论如何还是非常感谢你 :)! - Stephen Jenkins

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