简体   繁体   中英

Keydown event in a certain element of the DOM

Is it possible to capture the event of a combination of keyboard keys, in a single element of the DOM? I mean, what I want is that if I have a

<div id="k"><input id="text" type="text"></div>
<div id="j"><input id="text" type="text"></div>

And I just want to pick up the combination of keys Ctrl+H on the div with id "k"

Try using

<input id="text" type="text" onkeydown="myFunction1(event)"></div>
<div id="j"><input id="text" type="text"></div>
<script>
function myFunction1(ev) {console.log(ev);}
</script>

You can also read at W3schools

Solved adding a tabindex 1 to the ".upper-canvas " (yes with blank space) element and then binding the keydown on the ".upper-canvas " with jQuery.

var canvas = new fabric.Canvas('c');
$(document).ready(function(){
    $(".upper-canvas ").attr('tabindex', 1);
})
$(".upper-canvas ").on("keydown", function(event){
    console.log("Hi");
});

JSFiddle Solution

You can bind a keydown (or a keyup ) event. Then check if the Control key is pressed using event.ctrlKey property, and get the currently pressed key using event.key property. If both of them are pressed event.ctrlKey && event.key == 'h' will be true.

Notice that at the end of the event handler, I am calling event.preventDefault() . It prevents the default action, in this case, browser's shortcut of Ctrl + H from being activated.

 $("#k").on("keydown", function(event) { console.log(event.ctrlKey, event.key); if (event.ctrlKey && event.key == 'h') { alert("Ctrl + H pressed"); } event.preventDefault(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="k"><input id="text" type="text"></div> <div id="j"><input id="text" type="text"></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