如何检测到溢出的div已滚动到底部?

时间:2015-03-13 19:08:32

标签: javascript jquery html css

<div id="item-group" class="scroll-box"></div>

.scroll-box {
    overflow-x: hidden;
    overflow-y: auto;
    max-height: calc(100vh - 300px);
}

我想在用户滚动时加载项目。我通过检测它们何时滚动到屏幕底部来促进这一点。我一直试图用div元素做同样的事情而且无法弄明白。

1 个答案:

答案 0 :(得分:0)

这是我最近写的jquery脚本,当我滚动时获得9gag帖子。我希望它对你有所帮助:

注意检查的魔力是否在$(window).scroll函数中滚动到底部

<script>
    var nextPageId = '0'
        function loadNextPage(){
            $.getJSON("http://infinigag.eu01.aws.af.cm/trending/"+nextPageId, function(response){
                $.each(response.data, function(){
                    var $img = $('<img/>', {src: this.images.large})
                    $('body').append($img)
                })
                nextPageId = response.paging.next
            })
        }
        loadNextPage()
        var debounceNextPage = debounce(loadNextPage, 100)

        var $document = $(document)
        var $window = $(window)
        $(window).scroll(function(e){
            // console.log(e)
            if($document.height() - $window.scrollTop() == $window.height()){
                console.log("bottom");

                // loadNextPage()
                debounceNextPage()
            }
        })
        // Returns a function, that, as long as it continues to be invoked, will not
        // be triggered. The function will be called after it stops being called for
        // N milliseconds. If `immediate` is passed, trigger the function on the
        // leading edge, instead of the trailing.
        function debounce(func, wait, immediate) {
            var timeout;
            return function() {
                var context = this, args = arguments;
                var later = function() {
                    timeout = null;
                    if (!immediate) func.apply(context, args);
                };
                var callNow = immediate && !timeout;
                clearTimeout(timeout);
                timeout = setTimeout(later, wait);
                if (callNow) func.apply(context, args);
            };
        };
    </script>

修改

$(".box").scroll(function() {
    if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
        $("span").show();    
    } else {
        $("span").hide();
    }
});