简体   繁体   中英

Disable shortcut in textarea and input

I have this javascript that allows me to place the shortcut, but I want to deactivate them in the textarea and input

//press A for back to top
jQuery(document).keydown(function(e){
    var target = e.target || e.srcElement;
    if ( target.tagName !== "TEXTAREA" || target.tagName === "INPUT" ) {
            if(e.which == 84) {
                $("html, body").animate({ scrollTop: 0 }, 500);
                return false;
            }
    }
});

but because if I insert ( target.tagName !== "TEXTAREA" || target.tagName === "INPUT" ) the script does not work? how do I fix?

You have a wrong condition, the right one is:

if ( target.tagName != "TEXTAREA" && target.tagName != "INPUT" ) {...}

Also the Unicode value of 'A' is 65, 84 is for 'T'.

You can simplify you code to

//press A for back to top
$(document).keydown(function(e){
console.log(e);
    if(e.which == 65 && e.target.tagName !== 'INPUT'&& e.target.tagName !== 'TEXTAREA') {
      $("html, body").stop().animate({ scrollTop: 0 }, 500);
      return false;
    }
});

By the way in your comment you wrote "press A to top" but your code use "t" charcode (84); correct charcode is 65.

Here a working jsfiddle

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