2

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

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

        if (event == LETTER_P) {
            // go to another page
        }
    }

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

4

4 回答 4

4

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

if (document.activeElement === document.body) {
    // Nothing is in focus
}
于 2012-06-05T22:47:49.780 回答
2

你可以尝试这样的事情:

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

    if (event == LETTER_P && document.activeElement.tagName == "input") {
        // go to another page
    }
}

我对您的代码的添加不需要任何库。

于 2012-06-05T22:47:59.530 回答
1

您可以:focus在 jQuery 中使用选择器。

if ( $( "input:focus, textarea:focus" ).length ) {
   // there is a focused element
}
于 2012-06-05T22:45:29.177 回答
1
if ( $('input:focus, select:focus').length){
   // there is a focused element which would respond to a keypress
}
于 2012-06-05T22:49:12.533 回答