简体   繁体   中英

Run keyup function() based on keyCode except in input field?

I want to add a quick button on the blog. Some buttons have their respective functions defined by the following code:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).keyup(function(cfunc) {
    if (cfunc.keyCode == 83) {
        alert("S button");
    }
    if (cfunc.keyCode == 84) {
        alert("T button");
    }
    if (cfunc.keyCode == 67) {
        alert("C button");
    }
});
</script>

The code above works well. But there is a bit of a problem. If we enter text into the input field, then this code will interfere. Can we just run code outside the input field?

For example:

<input type="text" placeholder="abcd test"/>

If we enter the text "abcd test" , it will appear alert several times. This is because there are buttons s, t, and c . How to fix this code?

An easy way to prevent that is by checking if an input or textarea is focused:

 $(document).keyup(function(cfunc) { if ($("textarea, input").is(":focus")) { return; } if (cfunc.keyCode == 83) { alert("S button"); } if (cfunc.keyCode == 84) { alert("T button"); } if (cfunc.keyCode == 67) { alert("C button"); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" /> <br /> <textarea>hey</textarea> 

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