【问题标题】:"User is typing" function in chat聊天中的“用户正在输入”功能
【发布时间】:2012-02-16 08:10:39
【问题描述】:

我正在尝试在聊天中添加“用户正在输入”功能;用 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. 如果我停下来思考一下我的拼写,看起来我已经停止打字了。是否有更相关且更简单的方法来设置此功能?是否有可能的代码:

    • 文本框不为空(用户按下任意键开始输入)-> 消息:用户正在输入。
    • 文本框为空 -> 消息:用户没有输入。
    • 文本框不为空,但用户超过 5 秒没有按任何键 -> 消息:用户没有输入。
  2. 这表明我正在打字;我该如何实现它或在哪里实现它,以便在我的聊天框中看到“X 用户正在输入”而不是“我自己正在输入”。其他用户也一样,他应该收到一条关于我正在打字/不打字的消息,而不是关于他自己的消息。

谢谢。

【问题讨论】:

  • 为你+1 ..你找到解决方案了吗?因为我也需要和你一样的东西?
  • 有人把发送数据的ajax代码放在哪里

标签: ajax chat


【解决方案1】:

我创建了一个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);

【讨论】:

  • 有人把发送数据的ajax代码放在哪里
  • 这是完美的......但我想问你是否知道数据库将如何循环......如果正在输入,我如何让用户正在输入其他用户。??跨度>
  • @jamesOduro 可能通过套接字发送打字数据比插入数据库更好。
【解决方案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>

【讨论】:

  • 简单的 Javascript + HTML 就足够了。
  • 我发现在我的浏览器中 onkeypress 不包括退格、删除、箭头键或 shift,(但这可能不是问题。)
【解决方案3】:

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
     }
&lt;input id="chat-message-input" type="text" placeholder="Enter Message..." autofocus style="width: 50%; padding: 8px;"&gt;

【讨论】:

    【解决方案4】:

    有一个漂亮的库插件叫做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 并将 typing 设置为 true 以防止再次调用它。 然后调用 typingStopped,但只会在 5000 毫秒后调用包装在 _.debounce 中的函数,该函数作为 _.debounce 的第二个参数给出。但是,如果您再次调用 typingStopped,它会将倒计时重置回原来的 5000 毫秒。由于在每个输入上都会调用 typingStopped,因此它只会在两次按键之间的整整 5 秒后执行 typing = false。

    【讨论】:

      【解决方案5】:

      您可以使用 JQuery 而不是 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");
          }
      });
      

      【讨论】:

      • 我们如何将它传递给其他聊天者?我认为这将显示我打字的活动。
      猜你喜欢
      • 1970-01-01
      • 2020-02-10
      • 1970-01-01
      • 1970-01-01
      • 2016-02-02
      • 2011-05-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多