“用户在聊天中输入”功能

时间:2012-01-22 19:12:38

标签: ajax chat

我试图在聊天中添加"用户正在输入"功能;用PHP + MySQL / Ajax编写的聊天。

它应该如何运作:

- 当我的聊天伙伴X开始输入时,我会在聊天框中看到:" X正在输入"

- 当我(姓名Y)打字时,他在聊天框中看到:" Y正在打字" (就像Yahoo Messenger一样)。

到目前为止我尝试过的代码:

<script type="text/javascript" language="javascript">
    var timer = 0;

    function reduceTimer() {
        timer = timer - 1;
        isTyping(true);
    }

    function isTyping(val) {
        if (val == 'true') {
            document.getElementById('typing_on').innerHTML = "User is typing...";
        } else {

            if (timer <= 0) {
                document.getElementById('typing_on').innerHTML = "No one is typing -blank space.";
            } else {
                setTimeout("reduceTimer();", 500);
            }
        }
    }
</script>

<label>
    <textarea onkeypress="isTyping('true'); timer=5;" onkeyup="isTyping('false')" name="textarea" id="textarea" cols="45" rows="5"></textarea>
</label>
<div id="typing_on">No one is typing -blank speace.</div>

问题:

  1. 如果我停下来思考我的拼写几秒钟,看起来我已经停止打字了。有没有更相关和更简单的方法来设置此功能?是否有可能的代码:

    • 文本框不为空(用户按任意键以便开始输入) - &gt;消息:用户正在输入。
    • 文字框为空 - &gt;消息:用户未输入。
    • 文本框不为空,但用户未按任何键超过5秒 - &gt;消息:用户未输入。
  2. 它告诉我自己正在打字;我怎么能实现它或在哪里,为了在我的聊天框中看到&#34; X用户正在键入&#34;而不是&#34;我自己正在打字&#34;。对于其他用户来说,他应该收到关于我输入/不打字的消息,而不是关于他自己。

  3. 谢谢。

6 个答案:

答案 0 :(得分:11)

我创建了一个可能对您有帮助的fiddle。我们的想法是使用javascript setInterval函数刷新活动消息。

var textarea = $('#textarea');
var typingStatus = $('#typing_on');
var lastTypedTime = new Date(0); // it's 01/01/1970, actually some time in the past
var typingDelayMillis = 5000; // how long user can "think about his spelling" before we show "No one is typing -blank space." message

function refreshTypingStatus() {
    if (!textarea.is(':focus') || textarea.val() == '' || new Date().getTime() - lastTypedTime.getTime() > typingDelayMillis) {
        typingStatus.html('No one is typing -blank space.');
    } else {
        typingStatus.html('User is typing...');
    }
}
function updateLastTypedTime() {
    lastTypedTime = new Date();
}

setInterval(refreshTypingStatus, 100);
textarea.keypress(updateLastTypedTime);
textarea.blur(refreshTypingStatus);

答案 1 :(得分:2)

     <script>
        function isTyping() {
                document.getElementById('typing_on').innerHTML = "User is typing...! "; }

        function  notTyping (){
       document.getElementById('typing_on').innerHTML = "No one is typing ! "; }
    </script>

    <label>
        <textarea onkeypress="setTimeout(isTyping(),4000); setInterval(notTyping,5000)"  name="textarea" id="textarea" cols="45" rows="5"></textarea>
    </label>
    <div id="typing_on">No one is typing -blank speace.</div> 



    <!DOCTYPE html>
    <html>
       <head>
       </head>
       <body>

      <script>
        function isTyping() {
                document.getElementById('typing_on').innerHTML = "User is typing...! "; }
            
        function  notTyping (){
       document.getElementById('typing_on').innerHTML = "No one is typing ! "; }
    </script>

    <label>
        <textarea onkeypress="setTimeout(isTyping(),4000); setInterval(notTyping,5000)"  name="textarea" id="textarea" cols="45" rows="5"></textarea>
    </label>
    <div id="typing_on">No one is typing -blank speace.</div> 
       </body>
    </html>

答案 2 :(得分:1)

您可以使用JQuery来处理keypress事件而不是HTML。你可能会尝试这样的事情。然后在用户未输入时在div上设置默认的#typing。

//EXECUTES WHEN KEY IS PRESSED IN SPECIFIED ELEMENT
$("#textarea").keypress(function(){
numMiliseconds = 500;

//THIS IF STATEMENT EXECUTES IF USER CTRL-A DELETES THE TEXT BOX
if ($("textarea") == ""){
    $("#typing_on").text("User has cleared the text box");
}

$("#typing_on").text("User is typing").delay(numMiliseconds).queue(function(){
    $("#typing_on").text("User has stopped typing");
    }
});

答案 3 :(得分:0)

Theres是一个名为underscore.js

的漂亮的库插件

在其众多有用的函数中有一个叫_.debounce,可以像这样跟踪输入:

var typing, typingStarted, typingStopped;

typing = false;

typingStopped = _.debounce((function() {
  if (!typing) {
    return;
  }
  typing = false;
  console.log('typing is done so do what ever you need to do to notify it');
}), 5000);

typingStarted = function() {
  if (this.typing) {
    return;
  }
  typing = true;
  console.log('typing has started so do what ever you need to do to notify it');
};

document.querySelector("textarea").oninput = function(event) {
  typingStarted();
  typingStopped();
  return
};

这种方法的工作方式是在输入文本区域时调用typingStarted并将键入设置为true以防止再次调用它。 然后调用typingStopped,但只会在5000毫秒后调用_.debounce中包含的函数,该函数作为_.debounce的第二个参数给出。但是,如果再次调用typesStopped,它会将倒计时重置回原来的5000毫秒。由于在每个输入上调用了sortStopped,因此只有在按键之间完整的5秒后才会执行typing = false。

答案 4 :(得分:0)

var isTyping = false;
var isNotTyping;
  document.getElementById('chat-message-input').onkeypress = () => {
  sendIsTypingToUser()
  if (isNotTyping != undefined) clearTimeout(isNotTyping);
  isNotTyping = setTimeout(sendIsNotTyping, 900);
  };

  function sendIsTypingToUser(){
     if(!isTyping){
        console.log("IsTyping...........")
        isTyping = true
        }
     }
  function sendIsNotTyping(){
     console.log("Not Typing...........")
     isTyping = false
     }
<input id="chat-message-input" type="text" placeholder="Enter Message..." autofocus style="width: 50%; padding: 8px;">

答案 5 :(得分:0)

创建一个名为 unique_id 的行并将每个用户的唯一 id 存储在其中,您可以通过 php 的 rand() 函数来完成,然后创建名为 Typing 的第二行并将其默认值设置为 no,然后创建名为 as 的第三行ifyesthenwho 并将其默认值设置为 0,然后添加下面给出的代码。 将此javascript代码添加到用户聊天的聊天文件中(jquery使用版本3.6.0)

var textarea = $('#msgf');//where user type his/her message
var toshow = $('#typing');//where we show the typing message
var lastTypedTime = new Date(0); // it's 01/01/1970
var typingDelayMillis = 2000; // how long user can "think about his/her spelling"


function refreshTypingStatus() {
if (!textarea.is(':focus') || textarea.val() == '' || new Date().getTime() -         lastTypedTime.getTime() > typingDelayMillis) {
  $.post("php/tsd.php",
   {name: '<?php echo $user_id; ?>'},//user id is the unique id of the person by whom logged in user is chatting
   function(response){
   }
);
} 
else {
  $.post("php/ts.php",
   {name: '<?php echo $user_id; ?>'},//user id is the unique id of the person by whom logged in user is chatting
   function(response){
   }
);
}
}
function updateLastTypedTime() {
lastTypedTime = new Date();
}

setInterval(refreshTypingStatus, 100);
textarea.keypress(updateLastTypedTime);
textarea.blur(refreshTypingStatus);
setInterval(() => {
  $.post("php/shows.php",
   {name2: '<?php echo $user_id; ?>'},//user id is the unique id of the person by whom logged in user is chatting
   function(response){
     toshow.html(response);
   }
);
}, 800);

创建一个 ts.php 文件

<?php 
error_reporting(0); //to don't show any error to user
?>
<?php
session_start();
include_once 'config.php';//database configuration file
$outid = $_SESSION['unique_id'];//logged in user's unique id
$incid = $_POST['name'];//unique id of the user by which logged in users is chatting
$yes = 'yes';
$sql = "UPDATE `users` SET `typing` = '$yes' , `ifyesthenwho` = '$incid' WHERE     `users`.`unique_id` = $outid";
  $result = mysqli_query($conn, $sql);//running the sql query
?>

创建一个 tsd.php 文件

<?php 
error_reporting(0);//to don't show any error to user
?>
<?php
session_start();
include_once 'config.php';//database configuration file

$outid = $_SESSION['unique_id'];//logged in user's unique id
$incid = $_POST['name'];//unique id of the user by which logged in users is chatting
$yes = 'no';
$no = 0;
$sql = "UPDATE `users` SET `typing` = '$yes' , `ifyesthenwho` = '$no' WHERE `users`.`unique_id` = $outid";
  $result = mysqli_query($conn, $sql);//running the sql query
?>

创建一个shows.php文件

<?php 
error_reporting(0); //to don't show any error to user
?>
<?php
session_start();
include_once 'config.php';//database configuration file

$outid = $_SESSION['unique_id'];//logged in user's unique id
$incid = $_POST['name2'];//unique id of the user by which logged in users is chatting
$sql = "SELECT * FROM users WHERE  ifyesthenwho = '$outid'";
  $result = mysqli_query($conn, $sql);//running the sql query
$data = mysqli_fetch_assoc($result);//fetching data in associative array
if($data['unique_id'] == $incid){ 
    echo 'typing...';
}
?>

现在用户可以看到其他用户是否在打字