简体   繁体   中英

Detect text-input elements in javascript

In JavaScript, I would like to detect some key presses. But I want to ignore those keypresses that the user makes while typing into some kind of text input area. How can I achieve that?

I have tried

if (document.activeElement.nodeName == 'INPUT') {
    return;
}
if (document.activeElement.nodeName == 'TEXTAREA') {
    return;
}

which works in those two elements; but for example, the email-compose element in Inbox by Gmail is a DIV container. Do I want to exclude all active DIVs, though? Are there other HTML elements that are used to obtain key input? Is there any much different method that I may have overlooked?

First of all, I'd use jquery to normalize your events. From there, try testing $(event.target).is() :

Here is an example that has a div where all events are captured. Events for <input> elements are ignored, while others are not, including events for a <textarea> :

 $('#mydiv').keypress(function(event) { if ($(event.target).is('input')) { return true; } else { console.log('not an input box'); return false; } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="mydiv"> <input> <span>Spanning area</span> <textarea></textarea> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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