将内容附加到div并滚动/动画到底部

mow*_*gli 27 jquery scrolltop

我在添加新内容后尝试将div滚动到底部(使用append)

这是主要部分:

$('#textdiv').append('<p>Lorem ipsum dolor sit amet, solet nostrud concludaturque no eam. Ne quod recteque pri. Porro nulla zril mei eu. Eu nibh rebum pri, eu est maiorum menandri, ridens tamquam abhorreant te eum. Ipsum definiebas ad mel.</p>');

$('#textdiv').animate({scrollTop: $('#textdiv').height()}, 1000);
Run Code Online (Sandbox Code Playgroud)

在小提琴中查看/尝试:http://jsfiddle.net/5ucD3/7/

很多车..它不会滚动到底部(只有最初几个附加).当我向下滚动并添加新内容时,它会向上滚动.有时根本没有动画.

我如何让它始终工作?我想我必须以某种方式获得正确的高度,但不知道如何

mow*_*gli 49

我发现了一种有效的方法:

$('#textdiv').animate({scrollTop: $('#textdiv').prop("scrollHeight")}, 500);
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/5ucD3/13/


pac*_*nka 5

我又迟到了,但这是我的两分钱.

有时,仅使用一个读数来测量动态元素可能会导致错误,因为附加的内容可能很长,或者因为内容的请求($ .get,$.post,$ .ajax等等)仍然在空中.如果追加的字符串来自请求,那么您必须使用回调方法来附加响应.

你可以做的最好的事情是将它串起来,因为javascript"应该"解决函数同步时尚:

$("#textdiv").append('The longest string ever parsed goes here.')
.animate({scrollTop: $('#textdiv').prop("scrollHeight")}, 500);
Run Code Online (Sandbox Code Playgroud)

但是你是对的,这种方法往往是错误的,特别是在处理变异足够快的div时.

这就是为什么如果你想要更加确定工作完成,你可以使用一个间隔:

var scroll_to_bottom = function(element){
    var tries = 0, old_height = new_height = element.height();
    var intervalId = setInterval(function() {
        if( old_height != new_height ){    
            // Env loaded
            clearInterval(intervalId);
            element.animate({ scrollTop: new_height }, 'slow');
        }else if(tries >= 30){
            // Give up and scroll anyway
            clearInterval(intervalId);
            element.animate({ scrollTop: new_height }, 'slow');
        }else{
            new_height = content.height();
            tries++;
        }
    }, 100);
}

$('#textdiv').append('The longest string ever parsed goes here.');
scroll_to_bottom($('#textdiv'));
Run Code Online (Sandbox Code Playgroud)

这种方法无法击败回调或简单的函数排队,但如果您不确切知道追加何时结束,它就能解决问题.