我正在尝试在聊天中添加"用户输入"功能; 用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>
Run Code Online (Sandbox Code Playgroud)
问题:
如果我停下来思考我的拼写几秒钟,看起来我已经停止打字了.有没有更相关和更简单的方法来设置此功能?是否有可能的代码:
它告诉我自己正在打字; 我怎么能实现它或在哪里,为了在我的聊天框中看到"X用户正在打字"而不是"我自己正在打字".对于其他用户来说,他应该收到关于我输入/不打字的消息,而不是关于他自己.
谢谢.
Ram*_*źka 11
我创造了一个可能对你有帮助的小提琴.我们的想法是使用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);
Run Code Online (Sandbox Code Playgroud)
您可以使用 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");
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14996 次 |
| 最近记录: |