如何排除按键区域?

How to exclude an area for keydown?

我想在 div 中捕捉到按下的键(使用 tabindex),但在 div 中的输入文本获得焦点时却无法捕捉到。我尝试使用 jquery 的 .not(),但它实际上不起作用:

$('#content').not('input[type=text]').keydown( function(e) {
console.log(e.which);    
});

举个例子。 https://jsfiddle.net/kz6es4h0/

您可以检查 event.target 是否是 input 元素引发的,如果是则停止处理。试试这个:

$('#content').keydown(function (e) {
    if (e.target.tagName == 'INPUT')
        return;

    console.log(e.which);
});

Example fiddle

或者,您可以将单独的事件处理程序附加到 input 以停止 keydown 事件的事件传播:

$('input[type="text"]').keydown(function(e) {
    e.stopPropagation();
});

Example fiddle

我会在事件侦听器回调中放置一个 if 语句来检查输入此时是否有焦点

$('#content').keydown( function(e) {
    var hasFocus = $("input").is(":focus");
    if (!hasFocus){
        console.log(e.which);
    }
});