繁体   English   中英

是否有跨浏览器的解决方案来监控 document.activeElement 何时发生变化?

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

我真的在寻找适用于所有当前流行浏览器(IE9、Chrome、Firefox、Safari)并一直回到 IE8 的东西。

虽然,我一直在寻找一种方法来在 Flash 失去焦点后移动 object,但我发现所有这样做的历史方法都失败了。 我认为这是另一个安全问题。

所以,我现在正在寻找如何监视 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>

看来您可以结合使用捕获焦点/模糊和聚焦/聚焦(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 将几乎不需要清理。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM