你聊天“屏幕”应该是这样的:
<div id="chat">
<div class="wrapper">
<!-- chat messages go here -->
</div>
</div>
看跌溢出-Y:自动聊天,但留下的包装,因为它是。基于由$('#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);
然后,你需要绑定一个事件 '方法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/>');
});
下面是一个例子: http://jsfiddle.net/WVLE2/
检查http://stackoverflow.com/questions/7666649 /自动滚动到底部的分区 – Prusse
可能重复的[滚动到div的底部?](http://stackoverflow.com/questions/270612/scroll-to-bottom-of-div ) –