2011-12-12 110 views
5

我编写了一个聊天脚本,所有问题都与滚动DIV层有关。我下载了几个聊天脚本,仔细观察后发现了下面的内容。DIV如何在聊天脚本中滚动?

添加聊天行后,添加新线聊天时,滚动条不会向下滚动它的添加到DIV层的底部,因为滚动不会在制作时产生任何干扰。

我做了什么:

在我使用javascript向下滚动每隔固定的时间间隔之前。这样做我无法手动向上滚动查看过去的行(由于间隔刷新滚动条移动到设置位置)。后来我编写了一个可以向下滚动的javascript,但是这样做我只能向下滚动Chat sender side,但是当添加新的聊天行时,它不能向下滚动Chat receiver side

我下载了很多聊天脚本,并检查了如何管理这个特定的问题,但我找不到任何解决方案。我相信,它的jQuery的工作(不知道)可以有人告诉我如何解决这个问题?

如果您未能理解我的问题,我很遗憾,因为我无法在上面详细解释它。不过,我可以根据要求提供更多信息。

我正在使用的语言是ASP.NET,AJAX更新面板,用新值更新div的计时器滴答,JavaScripts直到现在只用于向下滚动元素。

+0

检查http://stackoverflow.com/questions/7666649 /自动滚动到底部的分区 – Prusse

+0

可能重复的[滚动到div的底部?](http://stackoverflow.com/questions/270612/scroll-to-bottom-of-div ) –

回答

4

你聊天“屏幕”应该是这样的:

<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/

+1

谢谢老兄,这对我有用。再次感谢。你清除了我几个月的怀疑。 –

+0

但是老兄,有没有一种方法可以实现使用javascripts? –

+0

你的意思是不使用jQuery? – benastan