只是想我会在 abject_error 给出的非常有用的答案上添加我的变体。这允许输入状态以及停止输入但输入了消息。我没有使用 socket.io,但你明白了。
var typingStatus=0; //0=Not typing: message blank, 1=typing, 2=typing: something there
var typingStatus_timeout = undefined;
//called when timeout kicks in that we've stopped typing
function function_typingStatus_timeout(){
//message entered
if ($('#chat_message').val().trim()) {
typingStatus=2;
//message is blank
} else {
typingStatus=0;
}
//send new status
connection.send(JSON.stringify({
action:'typingStatus',
typingStatus:typingStatus,
}));
}
$(document).ready(function(){
//TYPING
$('#chat_message').keydown(function(e) {
//only record typing if enter not pressed
if(e.which!=13 && e.keyCode!=13) {
//weren't typing before but are now
if (typingStatus!=1) {
//switch to 1 for in progress
typingStatus=1;
//broadcast
connection.send(JSON.stringify({
action:'typingStatus',
typingStatus:typingStatus,
}));
//were typing before and still are, clear the timeout, we're going to reset it in the next step
} else {
clearTimeout(typingStatus_timeout);
}
//either way, set the timeout to trigger after a second of not typing
typingStatus_timeout=setTimeout(function_typingStatus_timeout,1000);
//if enter was pressed we want to not have it register as a keydown at all. there's a separate function on keyup that looks for enter being pressed and sends the message
} else {
e.preventDefault();
}
});
});