检查两个元素是否未聚焦

Check that two elements aren't in focus

本文关键字:元素 是否 聚焦 两个 检查      更新时间:2023-09-26

我必须输入不能共享父元素的元素 #Core 和 #Price。我需要测试它们是否不在焦点上,以及它们何时没有运行函数。

我想我可以做一个检查,以确保当一个模糊时,另一个没有像这样被聚焦:

$('#Core').blur(function() {
    if(!$("#Price").is(":focus")) {
        getSellingPrice()
    }
});$('#Price').blur(function() {
    if(!$("#Core").is(":focus")) {
        getSellingPrice()
    }
});

但是,即使我将焦点放在另一个输入节点上,这似乎也会触发。我的猜测是,当模糊发生时,它会在尚未选择之前检查秒焦点。但我不确定如何更改代码以获得所需的行为,即在触发函数调用之前确保两个元素都不在焦点上。

非常感谢关于我如何完成此操作的任何想法或对当前代码不起作用的原因的见解。

您可以检查活动元素是否既不是

var elems = $('#Core, #Price').blur(function() {
    setTimeout(function() {
        if ( elems.toArray().indexOf(document.activeElement) === -1 ) {
            getSellingPrice();
        }
    });
});

但是您需要超时以确保设置焦点等。

模糊元素会将焦点传递给正文元素,然后再将其传输到单击的子元素。可怕的可能是一次性计时器,可用于通过检查单击的元素来解耦模糊。由模糊事件触发的概念代码(根据需要转换为您的编码标准、jQuery 和应用程序):

function blurred(el)
{
    setTimeout(checkFocus, 4); // ( 4 == Firefox default minimum)
}
function checkFocus()
{  var a = document.getElementById("a");
   var b = document.getElementById("b");
   var infocus = document.activeElement === a || document.activeElement === b;
   if(infocus)
      console.log( "One of them is in focus");
   else
      console.log(" Neither is in focus");
}

.HTML

a: <input id="a" type="text" onblur="blurred(this)"><br>
b: <input id="b" type="text" onblur="blurred(this)">