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

16 javascript document focus

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

虽然,我一直在寻找一种方法来在焦点失去焦点之后将焦点放在Flash移动对象上,但我发现所有历史方法都失败了.我认为这是另一个安全问题.

所以,我现在正在寻找如何监视document.activeElement的某种变更事件(虽然"改变"并没有真正发生).

Swa*_*oop 15

虽然@ 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>
Run Code Online (Sandbox Code Playgroud)

  • ```isSameActiveElement``` 是多余的 (4认同)

Jam*_*mes 8

看来您可以结合使用捕获焦点/模糊和焦点/焦点退出(IE)事件。也许是这样的:

window.addEventListener ?
  window.addEventListener('blur', blurHappened, true)
  : window.attachEvent('onfocusout', blurHappened);

function blurHappened() {
  console.log('document.activeElement changed');
}
Run Code Online (Sandbox Code Playgroud)

onfocusout将捕获冒泡的“模糊”,而常规的bluraddEventListener捕获“模糊”。

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