如何使用nodejssocket.io检查输入文本框或选项卡是否集中



下面的聊天代码运行良好。现在,我试图检查与我聊天的另一个最终用户的表单输入文本框和窗口选项卡是否在焦点上

这是我的问题和场景

两个用户正在聊天**(A先生和B先生(**现在A先生想检查或知道

B先生我试过这两组代码,但每次我发布消息时,它都会告诉我没有新消息

if(inputfocus_check){
// If the other end user is on input form chat box is focus, there's no need to show there's a new message
document.title = "No new Message";
}else{
// If the other end user input form chat box is not on focus, show there's a new message
document.title = "New message just arrive";
}

if (window.onfocus) {
// If the other end user is on focus, there's no need to show there's a new message
document.title = "No new Message";
}else{
// If the other end user is on another tab, show there's a new message
document.title = "New message just arrive";
}

这里是server.js

// Register events on socket connection
io.on('connection', function(socket){ 
socket.on('chatMessage', function(from, msg){
io.emit('chatMessage', from, msg);
});

index.js

var socket = io(); 
function submitfunction(){
var from = $('#user').val();
var message = $('#m').val();
socket.emit('chatMessage', from, message);
$('#m').val('').focus();
return false;
}
socket.on('chatMessage', function(from, msg){
$('#messages').append('<li><b style="color:' + color + '">' + from + '</b>: ' + msg + '</li>');

var inputfocus_check = $('#m').val('').focus();
if(inputfocus_check){
// If the other end user is on input form chat box is focus, there's no need to show there's a new message
document.title = "No new Message";
}else{
// If the other end user input form chat box is not on focus, show there's a new message
document.title = "New message just arrive";
}

/*
if (window.onfocus) {
// If the other end user is on focus, there's no need to show there's a new message
document.title = "No new Message";
}else{
// If the other end user is on another tab, show there's a new message
document.title = "New message just arrive";
}
*/

});

使用document.activeElement解决文本焦点问题

按照下面的代码

var el = document.getElementById('m');
// check for focus
var isFocused = (document.activeElement === el);

if (isFocused){
alert("focused");
}else{
alert("not focused")
}