即使向其添加内容,也要将滚动条固定到底部

cjm*_*ing 2 javascript jquery

为了更好地理解,我试图通过平滑过渡前一(上)聊天消息来实现聊天框.

这是http://jsfiddle.net/eEEGE/

当我点击"添加"时,我希望所有数字1 - 9向上滑动并在其下方附加10-12.

或者换句话说,我希望滚动条始终滚动固定在底部.

我知道我可以在追加后重新定位滚动条,但之后我将无法看到滑动动画.

代码参考

$(document).ready(function(){
    // set the default scroll bar to bottom of chat box
    $(".chat-list").scrollTop($(".chat-list")[0].scrollHeight);
    $("button").click(function(){
        $('.chat-list li:last-child').append('10<br/>11<br/>12');
        $('.chat-list li:last-child').show('slow');     
    });
});

<ul class="chat-list">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
    <li>8</li>
    <li>9</li>
    <li style="display:none"></li>
</ul>
<button>add</button>

.chat-list{
    height:100px;
    overflow:auto;
}
Run Code Online (Sandbox Code Playgroud)

luk*_*nis 5

    $(document).ready(function(){
        // set the default scroll bar to bottom of chat box
        $(".chat-list").scrollTop($(".chat-list")[0].scrollHeight);
        $("button").click(function(){
            $('.chat-list li:last-child').append('10<br/>11<br/>12');
// Do a callback for show()
            $('.chat-list li:last-child').show('slow', function() {
             $(".chat-list").scrollTop($(".chat-list")[0].scrollHeight);
            });        
        });
    });
Run Code Online (Sandbox Code Playgroud)

做一个回调到show()其将scrollTop()$('.chat-list')[0].scrollHeight.

如果你想要一个动画,那么只需动画scrollTop属性:

$(".chat-list").animate({
    scrollTop: $(".chat-list")[0].scrollHeight
 },'slow');
Run Code Online (Sandbox Code Playgroud)