Javascript 有没有办法确定是否没有元素处于焦点?

Mar*_*lec 2 javascript

我正在 HTML 页面中构建一些热键:

   $(document).bind('keypress', function (e) {
        var event = (e.keyCode ? e.keyCode : e.which);

        if (event == LETTER_P) {
            // go to another page
        }
    }
Run Code Online (Sandbox Code Playgroud)

但问题是,如果他们在页面上输入文本(在文本框元素等中)并点击字母“P”,他们就会转到另一个页面。我只希望当它们不在任何元素中时发生重定向。

dsl*_*slh 5

document.activeElement如今所有主流浏览器都支持。如果没有元素处于焦点activeElement,则将返回文档正文,因此:

if (document.activeElement === document.body) {
    // Nothing is in focus
}
Run Code Online (Sandbox Code Playgroud)