jQuery scrollTop不滚动到最后一个孩子 [英] jQuery scrollTop not scrolling to last-child

查看:78
本文介绍了jQuery scrollTop不滚动到最后一个孩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个聊天系统.我想发生的事情是当div开始溢出时,迫使它停留在最后一个

元素上.我在这里尝试了其他问题的一些建议,但仍然无法使它起作用.在#chat区域内,我正在使用ajax显示chat.txt文件.当您在#sendie文本区域中键入文本并按Enter键时,它将在chat.txt文件中附加您输入的文本.在chat.txt中的每个条目都有一个自动添加的<p>标记.因此,我需要它仅停留在最后一个<p>

I am creating a chat system. What I would like to have happen is when the div begins overflow, force it to stay on the last

element. I have tried several suggestions from other questions on here, and still cannot get it to work. Within the #chat-area i am using ajax to display a chat.txt file. When you type text into the #sendie textarea and press enter, it appends the chat.txt file with the text you entered. Each entry into the chat.txt tthen has a <p> tag automatically added to it. So I need it to just stay on the last <p>

这是我目前所在的位置:

Here is where I'm at currently:

HTML:

<div id="chatWrap"><div id="chat-area"></div></div>

<form id="send-message-area">
    <p>Your message: </p>
    <textarea id="sendie" maxlength = '200' ></textarea>
</form>

</div>

JS:

$(document).ready(function() {
    $('#chatWrap').animate({
        scrollTop: $('#chat-area p:last-child').position().top
    }, 1000);
});

CSS:

#chatWrap
{
width: 200px;
height: 200px;
box-shadow: 1px 1px 10px #333 inset;
color: white;
font-family: arial;
font-size: 14px;
overflow: auto;
}

#chat-area
{
padding-left: 11px;
}

#chat-area p:nth-child(even)
{
background: #961B10;
margin-left: -8px;
padding-left: 14px;
padding-top: 9px;
padding-bottom: 9px;
margin-top: 1px;
margin-bottom: -1px;
}

以下是输出:

<div id="chatWrap">
    <div id="chat-area">
        <p>Guest:hi </p>
        <p>Guest:hello </p>
        <p>Guest:Hey </p>
        <p>Guest:Hi </p>
        <p>Guest:Hello </p>
        <p>Guest:Hey </p>
        <p>Guest:Hi </p>
    </div>
</div>
<form id="send-message-area">
    <p>Your message: </p>
    <textarea id="sendie" maxlength="200"></textarea>
</form>

以下是AJAX:

var instanse = false;
var state;
var mes;
var file;

function Chat () {
    this.update = updateChat;
    this.send = sendChat;
    this.getState = getStateOfChat;
}

//gets the state of the chat
function getStateOfChat(){
if(!instanse){
     instanse = true;
     $.ajax({
           type: "POST",
           url: "process.php",
           data: {  
                    'function': 'getState',
                    'file': file
                    },
           dataType: "json",

           success: function(data){
               state = data.state;
               instanse = false;
           },
        });
}    
}

//Updates the chat
function updateChat(){
 if(!instanse){
     instanse = true;
     $.ajax({
           type: "POST",
           url: "process.php",
           data: {  
                    'function': 'update',
                    'state': state,
                    'file': file
                    },
           dataType: "json",
           success: function(data){
               if(data.text){
                    for (var i = 0; i < data.text.length; i++)          {
                        $('#chat-area').append($("<p>"+ data.text[i] +"</p>"));
                    }                                 
               }
               document.getElementById('chat-area').scrollTop =        document.getElementById('chat-area').scrollHeight;
               instanse = false;
               state = data.state;
           },
        });
 }
 else {
     setTimeout(updateChat, 3000);
 }
}

//send the message
function sendChat(message, nickname)
{       
updateChat();
 $.ajax({
       type: "POST",
       url: "process.php",
       data: {  
                'function': 'send',
                'message': message,
                'nickname': nickname,
                'file': file
             },
       dataType: "json",
       success: function(data){
           updateChat();
       },
    });
}

process.php:

process.php:

<?php

$function = $_POST['function'];

$log = array();

switch($function) {

     case('getState'):
         if(file_exists('chat.txt')){
           $lines = file('chat.txt');
         }
         $log['state'] = count($lines); 
         break; 

     case('update'):
        $state = $_POST['state'];
        if(file_exists('chat.txt')){
           $lines = file('chat.txt');
         }
         $count =  count($lines);
         if($state == $count){
             $log['state'] = $state;
             $log['text'] = false;

             }
             else{
                 $text= array();
                 $log['state'] = $state + count($lines) - $state;
                 foreach ($lines as $line_num => $line)
                   {
                       if($line_num >= $state){
                     $text[] =  $line = str_replace("\n", "", $line);
                       }

                    }
                 $log['text'] = $text; 
             }

         break;

     case('send'):
      $nickname = htmlentities(strip_tags($_POST['nickname']));
         $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
          $message =($_POST['message']);
     if(($message) != "\n"){

         if(preg_match($reg_exUrl, $message, $url)) {
            $message = preg_replace($reg_exUrl, '<a href="'.$url[0].'" target="_blank">'.$url[0].'</a>', $message);
            } 


         fwrite(fopen('chat.txt', 'a'), "". $nickname . ":" . $message = str_replace("\n", " ", $message) . "\n"); 
     }
         break;

}

echo json_encode($log);

?>

标头中的脚本:

// strip tags
    name = name.replace(/(<([^>]+)>)/ig,"");

    // display name on page
    $("#name-area").html("You are: <span>" + name + "</span>");

    // kick off chat
    var chat =  new Chat();
    $(function() {

         chat.getState(); 

         // watch textarea for key presses
         $("#sendie").keydown(function(event) {  

             var key = event.which;  

             //all keys including return.  
             if (key >= 33) {

                 var maxLength = $(this).attr("maxlength");  
                 var length = this.value.length;  

                 // don't allow new content if length is maxed out
                 if (length >= maxLength) {  
                     event.preventDefault();  
                 }  
              }  
});
         // watch textarea for release of key press
         $('#sendie').keyup(function(e) {   

              if (e.keyCode == 13) { 

                var text = $(this).val();
                var maxLength = $(this).attr("maxlength");  
                var length = text.length; 

                // send 
                if (length <= maxLength + 1) { 

                    chat.send(text, name);  
                    $(this).val("");

                } else {

                    $(this).val(text.substring(0, maxLength));

                }   


              }
         });

    });

再次

所以我发现了错误所在.

So I have discovered where the error is.

// kick off chat
    var chat =  new Chat();
ERROR: Chat is not defined
    $(function() {

推荐答案

您可以尝试如下更改updateChat()函数:

You could try change your updateChat() function, on sucess to be like this:

   success: function(data){
       if(data.text){
            for (var i = 0; i < data.text.length; i++)          {
                $('#chat-area').append($("<p>"+ data.text[i] +"</p>"));
            }
                $('#chatWrap').animate({
                   scrollTop: $('#chat-area').height()
                   }, 1000);
                })               
       }
       document.getElementById('chat-area').scrollTop =        document.getElementById('chat-area').scrollHeight;
       instanse = false;
       state = data.state;
   },

这行是做什么的? document.getElementById('chat-area').scrollTop = document.getElementById('chat-area').scrollHeight;我想您将不需要它.在尝试此更新之前先对其进行评论.

What does this line do? document.getElementById('chat-area').scrollTop = document.getElementById('chat-area').scrollHeight; I guess you won't need it. Comment it before try this update.

这篇关于jQuery scrollTop不滚动到最后一个孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆