滚动在错误的时间调用ajax

时间:2012-12-13 11:34:29

标签: javascript ajax jquery scrolltop

我试图在用户滚动到底部时使用以下函数加载ajax调用。但是,由于某种原因,该功能仅在用户向下滚动然后返回到顶部时触发ajax调用。这是我的代码:

$(window).scroll(function()
{   
if($(window).scrollTop() == $(document).height() - $(window).height())
{
    $('div#loadmoreajaxloader').show();
    $.ajax({
    url: "loadmore.php",
    success: function(html)
    {
        if(html)
        {
            var el = jQuery(html);
            jQuery(".content").append(el).masonry( 'appended', el, true );
            $('div#loadmoreajaxloader').hide();
        }else
        {
            $('div#loadmoreajaxloader').html('<center>No more posts to show.</center>');
        }
    }
    });
}
});

2 个答案:

答案 0 :(得分:0)

  $(window).scroll(function()
    {
        if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight)  {
           //do your stuff here

        }


    });

答案 1 :(得分:0)

检查如下:

  fetchContent = function() {
    if ($(window).scrollTop() + $(window).height() >= $(document).height()) {
        console.log('At bottom!!');

        // Remove the handler temporarily, so no more scroll events will fire.
        $(window).off('scroll', fetchContent);

        // Make the AJAX call.
        $('div#loadmoreajaxloader').show();
        $.ajax({
              url: "loadmore.php",
              success: function(html)
              {
                 if(html)
                 {
                     var el = jQuery(html);
                     jQuery(".content").append(el).masonry( 'appended', el, true );
                     $('div#loadmoreajaxloader').hide();
                 }else
                 {
                     $('div#loadmoreajaxloader').html('<center>No more posts to show.</center>');
                 }
                 // Re-attach the handler, so scroll events will fire again
                 $(window).on('scroll', fetchContent);
              }
             });
     }
  };

  $(function() {
      $(window).on('scroll', fetchContent);
  });

编辑:

我做了一个JSBin,当用户滚动到底部时显示一个div。你可以在这里看到它:http://jsbin.com/axobow/2

我知道这不是你需要的,但它应该给你一个想法。我还更新了代码,以便与最终产品的内容一致。

请检查。