繁体   English   中英

附加新消息时向下滚动底部

[英]scroll down bottom when new message append

在这里,我附上我的新消息。

<ul class="chat messages" id="get_AllMsg" style="overflow-y: scroll; height: 650px">

</ul>

在我成功的ajax电话

 var pre_content = $('.messages').html();
    var new_content = '<li class="clearfix">';
    new_content += '<span class="chat-img"><img src="" alt="User Avatar"></span>';
    new_content += '<div class="chat-body clearfix">
    <div class="header"><strong class="primary-font">' + name + '</strong> </div> <p>' + data.message + '</p> </div>';
    var content = pre_content + new_content;
        $('.messages').html(content);

在这里我使用jquery进行滚动,我想在发送新消息时自动滚动至底部

        $('.messages').animate({
            scrollTop: $('.messages').scrollHeight
        }, 1000);

您可以求和每个<li>元素的高度,然后使用它。 这是一个例子:

 var ht = 0; $(".messages li").each(function() { ht += $(this).height(); }); $(".messages").animate({scrollTop: ht}); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class="chat messages" id="get_AllMsg" style="overflow-y: scroll; height: 30px"> <li>example</li> <li>example</li> <li>example</li> <li>example</li> <li>example</li> <li>example</li> <li>example</li> <li>example</li> <li>example</li> <li>example</li> <li>example</li> <li>example</li> </ul> 

您应该使用$('.messages')[0].scrollHeight而不是$('.messages').scrollHeight

 $('.messages').animate({ scrollTop: $('.messages')[0].scrollHeight }, 1000); 
 .messages { width: 200px; background: red; } li { height: 1000px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class="chat messages" id="get_AllMsg" style="overflow-y: scroll; height: 650px"> <li></li> </ul> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM