最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Use jQuery to detect when an element is near the bottom of the page - Stack Overflow

programmeradmin2浏览0评论

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:

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

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:

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

Share Improve this question asked May 15, 2013 at 16:06 Stephen JenkinsStephen Jenkins 1,8363 gold badges26 silver badges40 bronze badges 1
  • This might help : stackoverflow.com/a/3898152/1823841 – palaѕн Commented May 15, 2013 at 16:14
Add a comment  | 

2 Answers 2

Reset to default 15

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

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

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

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

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

评论列表(0)

  1. 暂无评论