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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16569941/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 05:09:58  来源:igfitidea点击:

Use jQuery to detect when an element is near the bottom of the page

javascriptjquery

提问by Halcyon991

I've got a script that works out the distance of a list of elements from the top of the page, but I am unsure how to detect it's distance from the bottom. When it hits the bottom (well, 20px before the bottom) I want to fire an event and fade it out:

我有一个脚本可以计算元素列表与页面顶部的距离,但我不确定如何检测它与底部的距离。当它到达底部时(好吧,底部前 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)
        }
    })
})

If anyone has any advice, much appreciated. I'm looping through the elements to detect it, so when one of them hits 20px from the bottom, I want to fade it out. Thanks!

如果有人有任何建议,非常感谢。我循环遍历元素来检测它,所以当其中一个元素到达底部 20 像素时,我想将其淡出。谢谢!

回答by Bruno Croys Felthes

You can use the jQuery function height()at your calculations, like:

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

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

Specifically, if you want to detect if the top of the element is near to the bottom of the page, you can use this calc:

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

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

回答by Johan Rheeder

Halcyon,

宁静,

I am not sure what you want to fire but you can test the bottom of the page like this

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

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

Reason being is jQuery finds bottom of the page based upon its height

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

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