如何使用/ jQuery加载ajax数据淡入并滚动到最新项目

时间:2015-03-11 05:09:45

标签: jquery ajax jquery-ajaxq

让它几乎正常工作,它一次将最新的帖子3加载到#posts div中。但是我似乎无法弄清楚如果加载新帖子后如何向下滚动[所以它们都可见]

// infinite scrolling on homepage
$('.load-more').click(function(e) {

    var $this = $(this);

    var offset = $this.data('offset') + 3;

    var myProperties = {
        snippet: 'infiniteScroll',
        limit: 3,
        offset: offset,
        parents: 22,
        depth: 999,
        sortby: 'publishedon',
        showHidden: 1,
        debug: 1,
        tpl: 'infiniteHomePageTpl'
        };

    $.ajax({
        type: "POST",
        url: "/ajax.processor",
        data: myProperties,
        dataType: "json",

        success: function(response) {

            console.log(response);
            var newposts = response.posts;
            $(newposts).hide().appendTo('#posts').fadeIn(800);;

            if(response.lastpost){
                console.log('nodata');
                $this.attr('disabled', 'disabled');
            }

            // scroll to last posts (not working)
            $('#posts').animate({scrollTop: $('#posts').get(0).scrollHeight}, 300);

            // Update the offset
            $this.data('offset', offset);
        },

        error: function(response){
            console.log(response);
        },

    }).fail(function(jqXHR,textStatus,errorThrown) {
        console.log(errorThrown);
    }); // ajax

}); // load more

我不确定我是否正确理解了scrollTop功能,我是否需要将它应用于我添加的项目或我将它们添加到容器中?

Added Fiddle

1 个答案:

答案 0 :(得分:0)

使用此

 var post= $('#posts');
  var height = post[0].scrollHeight;
  post.scrollTop(height);

在Css中添加此代码

 #posts{
   width: 200px;
   height: 300px;
   overflow-y: scroll;
 }