Javascript 捕获 DIV 元素上的按键(或按键)事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3149362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Capture key press (or keydown) event on DIV element
提问by Lalchand
How do you trap the keypress or key down event on a DIV element (using jQuery)?
你如何在 DIV 元素上捕获按键或按键事件(使用 jQuery)?
What is required to give the DIV element focus?
需要什么才能使 DIV 元素成为焦点?
回答by helle
(1) Set the tabindexattribute:
(1) 设置tabindex属性:
<div id="mydiv" tabindex="0" />
(2) Bind to keydown:
(2) 绑定到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 divfocus border, set outline: nonein the CSS.
要删除 - 如果您不喜欢它 -在 CSS 中div设置的焦点边框outline: none。
See the table of keycodesfor more keyCodepossibilities.
有关更多可能性,请参阅键码表keyCode。
All of the code assuming you use jQuery.
所有代码都假设您使用 jQuery。
#回答by Илья Зеленько
Here example on plain JS:
这里是纯 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>
回答by nkshio
tabindexHTML attribute indicates if its element can be focused, and if/where it participates in sequential keyboard navigation (usually with the Tabkey). Read MDN Web Docsfor full reference.
tabindexHTML 属性指示其元素是否可以聚焦,以及它是否/在何处参与顺序键盘导航(通常使用Tab键)。阅读MDN Web 文档以获取完整参考。
Using Jquery
使用 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
使用 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>

