我试图在溢出时为聊天框滚动制作一个 DIV,但不幸的是它很快就停止了,我不知道为什么。这是我的代码。
谁能告诉我哪里出了问题以及如何解决?现在发生的事情是它会向下滚动一会儿,然后它会停止滚动。我已经被这个问题困了将近一个小时了。
最佳答案
虽然目前我不确定您自己的尝试失败的原因(虽然我猜这是变量 CHATBOX_ID
的问题,但这只是因为您没有显示它的来历从),这个版本有效。尽管有几个假设(我稍后会解释):
var chatContentHeight, scrollVal;
var chatHeight = $('#chat').height();
$('#message').keyup(
function(e) {
chatContentHeight = 0;
if (e.keyCode == '13') { // assuming you want messages submitted on hitting 'enter'
newMsg = $(this).val();
$('<div />').text(newMsg).appendTo('#chat');
$(this).val('');
$('#chat > div').each(
function() {
chatContentHeight = chatContentHeight + $(this).outerHeight();
});
if (chatContentHeight > chatHeight) { // checking whether or not scrolling is needed
scrollVal = (chatContentHeight - chatHeight); // defines the amount to scroll
$('#chat').scrollTop(scrollVal);
}
}
});
我的假设是:
- 您希望在点击enter时提交消息,
- 如果您愿意/想使用
div
来包含消息,我个人更喜欢使用dl
或ol
,但使用这些元素似乎使演示有点复杂,尽管它们完全可以使用。
如果您想要一个解释(或者,至少,如果您想帮助我们能够提供一个解释),您至少需要发布完整的 jQuery/JavaScript 或指向重现您问题的现场演示的链接(在您自己的服务器上或在 JS Fiddle 或类似位置)。
引用资料:
-
keyup()
. -
val()
. -
appendTo()
. -
each()
. -
scrollTop()
.
关于css - DIV 溢出滚动停止短,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6431829/