为什么 document.activeElement.matches(':focus') 返回 false?



我有这个片段:

function focusChanged(event)
{
//  setTimeout(function() {
console.log('focus now: ' + document.activeElement);
console.log(document.activeElement.matches(':focus'));
//}, 0);
}
<div class="editor one" contenteditable="true" onfocus="focusChanged(event)">click here to focus</div>

在没有超时的情况下,以下返回false:

document.activeElement.matches(':focus')
false

控制台打开(如document.activeElement.matches(:focus(中所建议的(。为什么会这样?(

这种情况发生在WebKit/Safari中。有人能解释为什么会发生这种事吗?谢谢

编辑:

也许还有一些背景:我是在遇到jQuery的.is(':focus')问题后才发现上述问题的。我有一个旧项目仍然使用jQuery v1.9.1。

此代码:$('.editor').is(':focus')多年来运行良好。只有在macOS Catalina 10.15.4的最新更新中,即使div有焦点,也开始返回false。然后我尝试使用一个普通的JS解决方案,遇到了上面的问题。

有些事件在浏览器之间的实现略有不同。在基于WebKit的浏览器上,元素在事件处理程序运行后才被视为"集中",但在基于Blink的浏览器(Chrome等(上,尽管它是WebKit的分支(一部分(,但在事件处理过程中它被视为集中。

您允许事件完成的解决方案似乎是一个可靠的解决方案。

最新更新