我编写了一个聊天脚本,所有问题都与滚动 DIV 层有关。我下载了几个聊天脚本,仔细观察后发现如下。
当添加新的聊天行时,滚动条不会在添加聊天行后向下滚动。它添加到 DIV 层的底部为卷轴在制作时不会造成任何干扰。
我做了什么:
在我使用 javascript 为每个固定间隔向下滚动之前。这样做我无法手动向上滚动以查看过去的行(由于间隔刷新滚动条移动到设置位置)。后来我编写了一个可以向下滚动的 javascript OnClientClick
但是这样做我只能向下滚动 Chat sender side
但它不能在 Chat receiver side 向下滚动
添加新的聊天行时。
我下载了很多聊天脚本并检查了这个特定问题是如何管理的,但我找不到任何解决方案。我相当猜测这是 jQuery 的工作(不确定)有人能告诉我如何解决这个问题吗?
如果您未能理解我的问题,我很抱歉,因为我无法比上面更详细地解释它。不过,我可以根据要求为您提供更多信息。
我使用的语言是 ASP.NET、AJAX 更新面板、使用新值更新 div 的计时器滴答声,javascript 到目前为止仅用于向下滚动元素。
最佳答案
您的聊天“屏幕”应如下所示:
<div id="chat">
<div class="wrapper">
<!-- chat messages go here -->
</div>
</div>
将 overflow-y: auto 放在聊天中,但保持包装器不变。创建以一定间隔运行的函数,并根据 $('#chat').scrollTop() 方法返回的值添加或删除“atBottom”类以聊天“屏幕”。
monitor = function() {
var $this = $(this),
wrap = $this.find('.wrapper'),
height = $this.height(),
maxScroll = wrap.height() - height,
top = $this.scrollTop();
if (maxScroll === top) {
$this.addClass('atBottom');
} else {
$this.removeClass('atBottom');
}
}
window.setInterval(function() {
monitor.call($('#chat').get(0));
}, 350);
然后你需要绑定(bind)一个像这样工作的事件“addMessage”:
$('#chat').bind('addMessage', function(e, message) {
var $this = $(this),
// store whether it's at the bottom before appending the message
scroll = $this.hasClass('atBottom');
// then append the message
$this.find('.wrapper').append(message);
if (scroll) {
// measure the new maxScroll and scroll to it.
var wrap = $this.find('.wrapper'),
height = $this.height(),
maxScroll = wrap.height() - height
$this.scrollTop(maxScroll);
}
})
$('button').click(function() {
$('#chat').trigger('addMessage', 'asdgagasdg<br/>');
});
关于javascript - DIV 如何在聊天脚本中滚动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8477106/