【问题标题】:how to auto scroll down in div on content added?如何在添加内容的 div 中自动向下滚动?
【发布时间】:2014-07-13 11:33:21
【问题描述】:

我正在开发一个使用 jquery、php 和 ajax 的聊天程序。我的问题是,当用户输入味精并且聊天框溢出时,它应该在新味精输入和聊天框溢出时自动向下滚动。我试图实现的就是这个。

代码

 $.ajaxSetup ({
  cache: false
 });
$(document).ready(function(e) {


setInterval (function() {
    $('.main').load('display_messages.php');
},1000)

$(function() {
    //Function for press Return button
    $('#newMessageContent').keypress(function(e) {
        if (event.keyCode == 13 || !event.keyCode == all  ) {
                setTimeout (function() {
                    $('.main').load('display_messages.php');
                    setTimeout (function() {
                        $('.main p:last').addClass('animated fadeIn');
                    },20)
                },50);
            //$('.main').stop().animate({scrollTop:$('.main')[0].scrollHeight}, 1000);
        }
    });
    // Functions for click button
    $('#newMessageSend').click(function() {
        setTimeout (function() {
                $('.main').load('display_messages.php');
                setTimeout (function() {
                    $('.main p:last').addClass('animated fadeIn');
                },20)
        },50);
        //$('.main').stop().animate({scrollTop:$('.main')[0].scrollHeight}, 1000);
    });




    var chckIt = setInterval(function(){
         $('.main').one('DOMSubtreeModified',function(){
             setTimeout(function() {
                $('.main').stop().animate({scrollTop:$('.main')[0].scrollHeight}, 1000);
             },500);
         })
    },1000)

    $('.main').on('scroll',function(){
        if ( $('.main').scrollTop() === 0 ){
        clearInterval(chckIt);
        }
    });

 });    

});

它有一些错误。它会自动向下滚动,但它会一次又一次地重复,不会停止,如果你愿意,你不能向上滚动来查看旧的消息。

然后我用这个函数$('.main').on('scroll',function(){ if ( $('.main').scrollTop() === 0 ){ clearInterval(chckIt); } });来控制它,但它没用。

这里是html。

代码

        <div class="chatBox">
    <div class="chatlogo">
            <embed src="test2.swf" play="true" class="vid2" loop="true" width="180" height="50" salign="C" scale="ShowAll" id="vid_2" quality="High" wmode="transparent" name="vid_2" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash">
      </div>
        <div class="user">

        <form name="signIn" id="signInForm" action="signout_delete_content.php" method="post" onSubmit="return false">
            <span class="error animated">Invalid uername</span>
            <input name="username" type="text" id="username" placeholder="Enter username" size="13px" onClick='document.username.value = "" '>
            <input type="submit" id="signIn" value="SING IN">
        </form>
            <span class="welcome"></span>
            <input type="button" id="signOut" value="SIGN OUT" onclick="window.location.reload();">
        </div>
        <div class="main">
            <p>Admistrator: Hello msgs here.</p>
        </div>
        <div class="messageBox">
            <form name="messageBoxSignInForm" id="messageBoxSignInForm" onSubmit="return false">
            <input type="submit" id="messageBoxSignIn" value="Sign In to Enter Chat">
            </form>
          <form name="newMessage" class="newMessage" action="" onSubmit="return false">
            <textarea name="newMessageContent" id="newMessageContent" placeholder="Enter your message here.">Enter your message here</textarea>
            <input type="submit" id="newMessageSend" value="Send">

          </form>
      </div>
    </div>

任何帮助将不胜感激。谢谢

【问题讨论】:

  • 检查this answer 如果您觉得它没有用,请构建一个简单的jBinjsFiddle,因为这样会更容易测试您的代码。
  • 它也有php编码,所以不能在jsfiddle中使用
  • 可以模拟添加内容;因为这个...how to auto scroll down in div 与 PHP 无关 :)
  • php文件是通过ajax加载的,代码里没看到吗?
  • 好吧,我看到了代码...这个$('.main').load('display_messages.php') 可以用somebuttoon.onclick = function() { populate that div with some text 模拟,就是这样:)

标签: php jquery html ajax chat


【解决方案1】:

您无法向上滚动,因为您一直在触发 load('display_message.php'),这将触发 'DOMSubtreeModified' 事件。因此,您不能依赖“DOMSubtreeModified”而必须通过其他方式检查新消息。例如,您可以计算每个“display_message.php”的消息数量并检查差异。

var old = 0, new = 0;
$('#newMessageSend').click(function() {
    setTimeout (function() {
            $('.main').load('display_messages.php', chckIt);
            setTimeout (function() {
                $('.main p:last').addClass('animated fadeIn');
            },20)
    },50);
    //$('.main').stop().animate({scrollTop:$('.main')[0].scrollHeight}, 1000);
});


var chckIt = function(){
    new = $('.main').children().length;
         if (new > old)
         {
             old = new;
             setTimeout(function() {
                $('.main').stop().animate({scrollTop:$('.main')[0].scrollHeight}, 1000);
             },500);
         }
     };

【讨论】:

  • 这一行有语法错误var old = 0, new = 0;
  • 它的工作,但我希望它在两个浏览器上显示消息,并在两个用户之间的两个浏览器上向下滚动。怎么做?你测试了吗?
  • 如果没有此代码,是否会在 2 个浏览器上显示消息?
  • 这可能与您的服务器端有关。服务端是怎么做的?
【解决方案2】:

你是对的,我之前的回答不起作用..

$('.messageBox').scrollTop($('.messageBox')[0].scrollHeight)

这很好用:

jsfiddle: http://jsfiddle.net/Lh4TN/6/

【讨论】:

  • 保持这个方法单独运行,每当有新消息出现时将其添加到消息框..并将这个超时功能取出到某个打开的地方..不要与其他功能混合使用。或者,如果您使用的是 HTML5,请为此目的使用 SSE 事件。
  • 这是因为你通过load函数不断在.main中加载元素,这会触发DOMSubtreeModified。
  • 那么解决办法是什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-13
相关资源
最近更新 更多