首页 > 解决方案 > 向下滚动时无限滚动不起作用

问题描述

我有一个代码无限滚动,但我有一个问题。为什么我的代码在向上滚动而不是向下滚动时工作?

<script type="text/javascript">
$(document).ready(function(){
    $(window).scroll(function(){
        var lastID = $('.load-more').attr('lastID');
        if(($(window).scrollTop() == $(document).height() - $(window).height()) && (lastID != 0)){
     //Why work when scroll up? i want this work when scroll down
            $.ajax({
                type:'POST',
                url:'<?php echo base_url('berita/load_more'); ?>',
                data:'id='+lastID,
                beforeSend:function(){
                    $('.load-more').show();
                },
                success:function(html){
                    $('.load-more').remove();
                    $('#postList').append(html);
                }
            });
        }
    });
});
</script>

在https://tabungamal.id/berita/infinite上查看现场演示

标签: javascriptinfinite-scroll

解决方案


使用此代码重试

function scrollEvt(){
    var lastID = $('.load-more').attr('lastID');
    if(((window.innerHeight + window.scrollY) >= document.body.offsetHeight) && (lastID != 0)){
        $(window).off('scroll');
        $.ajax({
            type:'POST',
            url:'https://tabungamal.id/berita/load_more',
            data:'id='+lastID,
            beforeSend:function(){
                $('.load-more').show();
            },
            success:function(html){
                $('.load-more').remove();
                $('#postList').append(html);
                $(window).scroll(scrollEvt);
            }
        });
    }


}

$(document).ready(function(){

    $(window).scroll(scrollEvt);

});    

推荐阅读