Capture key press (or keydown) event on DIV element

我是研究僧i 提交于 2019-12-16 23:57:32

问题


How do you trap the keypress or key down event on a DIV element (using jQuery)?

What is required to give the DIV element focus?


回答1:


(1) Set the tabindex attribute:

<div id="mydiv" tabindex="0" />

(2) Bind to keydown:

 $('#mydiv').on('keydown', function(event) {
    //console.log(event.keyCode);
    switch(event.keyCode){
       //....your actions for the keys .....
    }
 });

To set the focus on start:

$(function() {
   $('#mydiv').focus();
});

To remove - if you don't like it - the div focus border, set outline: none in the CSS.

See the table of keycodes for more keyCode possibilities.

All of the code assuming you use jQuery.

#


回答2:


tabindex HTML attribute indicates if its element can be focused, and if/where it participates in sequential keyboard navigation (usually with the Tab key). Read MDN Web Docs for full reference.

Using Jquery

$( "#division" ).keydown(function(evt) {
    evt = evt || window.event;
    console.log("keydown: " + evt.keyCode);
});
#division {
  width: 90px;
  height: 30px;
  background: lightgrey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="division" tabindex="0"></div>

Using JavaScript

var el = document.getElementById("division");

el.onkeydown = function(evt) {
    evt = evt || window.event;
    console.log("keydown: " + evt.keyCode);
};
#division {
  width: 90px;
  height: 30px;
  background: lightgrey;
}
<div id="division" tabindex="0"></div>



回答3:


Here example on plain JS:

document.querySelector('#myDiv').addEventListener('keyup', function (e) {
  console.log(e.key)
})
#myDiv {
  outline: none;
}
<div 
  id="myDiv"
  tabindex="0"
>
  Press me and start typing
</div>


来源:https://stackoverflow.com/questions/3149362/capture-key-press-or-keydown-event-on-div-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!