我有正在扮演聊天角色的文字区域。我试图让它在每条新消息的底部停留,但没有成功。我做的是:
var chatBox = $('.chat-box');
var body = $('body');
var chatContent = $('<textarea>', {
rows : 11,
"class" : 'chat-content',
placeholder : 'Find your friens here .. ',
readonly : true,
id : 'cont'
});
//load last 10 messages on ready
$.ajax({
method : 'POST',
url : '../site/load-messages',
dataType : 'json',
success : function (data) {
$.each(data.reverse(), function (key, value) {
chatContent.val(chatContent.val() + value.message_author + " : " + value.message_content + '\n');
});
}
});
var chatMessage = $('<input>', {
type : 'text',
"class" : 'chat-message',
id : 'chat-message'
});
var chatButton = $('<input>', {
type : 'button',
value : 'Send',
"class" : 'chat-button',
id : 'chat-button'
});
chatBox.hover(function () {
$(this).animate({height : '300px'}, 'slow');
chatBox.append(chatContent)
.append(chatMessage)
.append(chatButton);
}, function () {
$(this).animate({height : '40px'}, 'slow');
});
body.keypress(function (e) {
if(e.which == 13)
{
return sendMessage();
}
});
body.on('click', '#chat-button', function () {
return sendMessage();
});
function sendMessage() {
var message = $('#chat-message').val();
var chat = $('#cont');
$.ajax({
method : 'POST',
url : '../site/add-message?message=' + message,
dataType : 'json',
success : function ( data ) {
chat.val(chat.val() + data.message_author + ' : ' + data.message_content + '\n');
$('#chat-message').val('');
chat.scrollTop = chat.scrollHeight;
}
}) ;
}
chat
是动态创建的文本区域。是因为我的滚动不起作用吗?或者也许我做错了?感谢每一个建议!
答案 0 :(得分:1)
尝试将chat.scrollTop = chat.scrollHeight;
替换为chat.scrollTop(chat.prop('scrollHeight') - chat.height());