我正在尝试在聊天中添加“用户正在输入”功能;用 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>
问题:
谢谢你。
最佳答案
有一个漂亮的库插件,叫做 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 。
关于ajax - "User is typing"聊天功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8963810/