Mad*_*er. 5 javascript ajax chat
我编写了一个聊天脚本,所有问题都是滚动DIV层.我下载了几个聊天脚本,仔细观察后发现了下面的内容.
当添加新的聊天行时,添加聊天行后滚动条不会向下滚动.它作为滚动添加到DIV层的底部,在制作时不会产生任何干扰.
我做了什么:
之前我使用javascript向下滚动每个固定的间隔.这样做我无法手动向上滚动查看过去的行(由于间隔刷新滚动条移动到设置位置).后来我编写了一个可以向下滚动的javascript,OnClientClick但这样做我只能向下滚动,Chat sender side但是Chat receiver side当添加新的聊天行时它无法向下滚动.
我下载了很多聊天脚本,并检查了如何管理这个特定问题,但我找不到任何解决方案.我相信它的jQuery工作(不确定)任何人都可以告诉我如何解决这个问题?
如果你不理解我的问题,我很抱歉,因为我无法比上面更详细地解释它.但是我可以根据要求提供更多信息.
我使用的语言是ASP.NET,AJAX更新面板,用新值更新div的计时器刻度,javascripts直到现在才用于向下滚动元素.
您的聊天“屏幕”应如下所示:
<div id="chat">
<div class="wrapper">
<!-- chat messages go here -->
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
将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);
Run Code Online (Sandbox Code Playgroud)
然后您需要绑定一个事件“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/>');
});
Run Code Online (Sandbox Code Playgroud)
这是一个例子: http: //jsfiddle.net/WVLE2/