是否有跨浏览器的解决方案来监控document.activeElement何时更改

Is there a cross-browser solution for monitoring when the document.activeElement changes?

本文关键字:document 监控 activeElement 何时更 解决方案 浏览器 是否      更新时间:2023-09-26

我真的在寻找能与所有当前流行的浏览器(IE9、Chrome、Firefox、Safari)一起使用的东西,一直到IE8。

尽管我一直在寻找一种方法,在Flash移动对象失去焦点后将焦点设置在它上,但我发现所有历史上的方法都失败了。我认为这是另一个安全问题。

因此,我现在正在寻找如何监控document.activeElement的某种更改事件(尽管"更改"并没有真正发生)。

而@James上面的回答是正确的。我添加了更多的细节,使其成为一个完全有效的解决方案,同时也使用了focus事件。

<html>
<body>
    <input type="text" id="Text1" name ="Text1" value=""/>
    <input type="text" id="Text2" name ="Text2" value=""/>
    <SELECT><OPTION>ASDASD</OPTION><OPTION>A232</OPTION></SELECT>
    <INPUT TYPE="CHECKBOX" id="Check1"/>
    <INPUT type="TEXT" id="text3"/>
    <input type="radio"/>
    <div id="console"> </div>
    <textarea id="textarea1"> </textarea>
    <script>
        var lastActiveElement = document.activeElement;
        function detectBlur() {
            // Do logic related to blur using document.activeElement;
            // You can do change detection too using lastActiveElement as a history
        }
        function isSameActiveElement() {
            var currentActiveElement = document.activeElement;
            if(lastActiveElement != currentActiveElement) {
                lastActiveElement = currentActiveElement;
                return false;
            }
            return true;
        }
        function detectFocus() {
            // Add logic to detect focus and to see if it has changed or not from the lastActiveElement. 
        }
        function attachEvents() {
            window.addEventListener ? window.addEventListener('focus', detectFocus, true) : window.attachEvent('onfocusout', detectFocus);  
            window.addEventListener ? window.addEventListener('blur', detectBlur, true) : window.attachEvent('onblur', detectBlur);
        }
        attachEvents();
    </script>
</body>
</html>

似乎可以使用捕获focus/flur和focusin/focusout(IE)事件的组合。也许是这样的:

window.addEventListener ?
  window.addEventListener('blur', blurHappened, true)
  : window.attachEvent('onfocusout', blurHappened);
function blurHappened() {
  console.log('document.activeElement changed');
}

onfocusout将捕获起泡的"模糊",而addEventListener上的常规blur将捕获"模糊"。

您可能需要在blurHappened中添加其他检查。我不确定,因为我还没有测试。

您可以使用focusin事件侦听器捕获文档上的焦点更改。

document.addEventListener('focusin', () => {
  console.log('focus changed');
});
div {
  display: flex;
  flex-direction: column;
}
<div>
  <input type="text">
  <input type="text">
  <input type="text">
  <input type="text">
  <input type="text">
</div>

根据我的经验,关于跨浏览器问题的最佳信息来源是Quirksmode。这里有一个指向"显而易见"(但不可用)选项的链接——聚焦和模糊事件。

http://www.quirksmode.org/dom/events/blurfocus.html

奇怪的是,基于Webkit的浏览器是美中不足的。

另一种选择是使用间隔计时器来检查activeElement是否已更改,无论是作为您的唯一选项还是作为焦点/模糊的备份。(你也可以监听按键、鼠标点击和触摸,以检查activeElement是否发生了变化。)如果你涵盖了这些选项,你的intervalTimer就几乎不需要清理了。