简体   繁体   中英

Disable certain keys, but not for textarea and input

I've checked this wonderful websites database and somehow provided answers does not work.

To prevent glitches, by default I must disable arrow keys and spacebar. That works with this code:

window.addEventListener("keydown", function(e) {
    if([32, 37, 38, 39, 40].indexOf(e.keyCode) > -1) {
        e.preventDefault();
    }
}, false);

But arrow keys and space bar are necessary for certain areas of website (input and textarea fields). To allow, I did as follows:

window.addEventListener("keydown", function(e) {
    if([32, 37, 38, 39, 40].indexOf(e.keyCode) > -1) && ($(event.target)[0]!=$("textarea, input")[0])) {
        e.preventDefault();
    }
}, false);

But it does not seem to work. Help much appreciated!

In this case, one option you have is setting an event handler for all the textarea and input elements and utilizing event.stopPropagation() in order to prevent the window event handler from being fired. With this, the elements capture the keydown event and then tell the JavaScript engine not to fire other event handlers of elements that are higher in the DOM chain (such as the document or window).

window.addEventListener("keydown", function(e) {
    if([32, 37, 38, 39, 40].indexOf(e.keyCode) > -1) {
        e.preventDefault();
    }
}, false);

And with jQuery:

// Function gets run after document is loaded
$(function(){
   $("textarea, input").keydown(function(e){
      e.stopPropagation()
   })
});

Edit: working jsFiddle.

You can get the targetted element name using the nodeName property:

var targettedElement = $(event.target)[0].nodeName.toLowerCase(); // its uppercase by default

Then you can use that to check conditionally:

window.addEventListener("keydown", function(e) {
    var targettedElement = $(event.target)[0].nodeName.toLowerCase();
    if(
        [32, 37, 38, 39, 40].indexOf(e.keyCode) > -1
        && targettedElement != 'textarea'
        && targettedElement != 'input'
    ) {
        e.preventDefault();
    }
}, false);

Fiddle

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