每次li都添加到ul,滚动停留在同一个地方,如何在回发时始终将滚动移动到ul的底部以显示最新项目?
<ul id="discussion"></ul>
<script>
var usrName = "@HttpContext.Current.User.Identity.Name";
$(function () {
var chat = $.connection.chatHub;
chat.client.addNewMessageToPage = function (name, message) {
$('#discussion').append('<li style="left:5%"><strong>' + htmlEncode(name)
+ '</strong>: ' + htmlEncode(message) + '</li>');
};
$('#displayname').val(usrName);
$('#message').focus();
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
chat.server.send($('#displayname').val(), $('#message').val());
$('#message').val('').focus();
});
});
});
function htmlEncode(value) {
var encodedValue = $('<div />').text(value).html();
return encodedValue;
}
</script>
Andrew Walters的解决方案
// function that the hub call back to display messages.
chat.client.addNewMessageToPage = function (name, message) {
// Adds message
$('#discussion').append('<li style="left:5%"><strong>' + htmlEncode(name)
+ '</strong>: ' + htmlEncode(message) + '</li>');
//scrolls down after item is added
$("#discussion").scrollTop($("#discussion")[0].scrollHeight);
答案 0 :(得分:0)
添加每个项目后,您需要重新滚动。
$("#discussion").scrollTop($("#discussion")[0].scrollHeight);