Detecting when user scrolls to bottom of div with jQuery

前端 未结 15 1857
一个人的身影
一个人的身影 2020-11-22 14:47

I have a div box (called flux) with a variable amount of content inside. This divbox has overflow set to auto.

Now, what I am trying to do, is, when the use scroll t

15条回答
  •  执笔经年
    2020-11-22 15:19

    If you are not using Math.round() function the solution suggested by Dr.Molle will not work in some cases when a browser window has a zoom.

    For example $(this).scrollTop() + $(this).innerHeight() = 600

    $(this)[0].scrollHeight yields = 599.99998

    600 >= 599.99998 fails.

    Here is the correct code:

    jQuery(function($) {
        $('#flux').on('scroll', function() {
            if(Math.round($(this).scrollTop() + $(this).innerHeight(), 10) >= Math.round($(this)[0].scrollHeight, 10)) {
                alert('end reached');
            }
        })
    });
    

    You may also add some extra margin pixels if you do not need a strict condition

    var margin = 4
    
    jQuery(function($) {
        $('#flux').on('scroll', function() {
            if(Math.round($(this).scrollTop() + $(this).innerHeight(), 10) >= Math.round($(this)[0].scrollHeight, 10) - margin) {
                alert('end reached');
            }
        })
    });
    

提交回复
热议问题