javascript 如何将键盘事件绑定到 div 元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10722589/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 10:49:30  来源:igfitidea点击:

How to bind keyboard events to div elements?

javascriptjquery

提问by ilyes kooli

Is there a way to listen to keyboard events on a DIV element?

有没有办法在 DIV 元素上监听键盘事件?

My code:

我的代码:

?<div id="div" style="height:50px" class="ui-widget-content"></div>
<input id="input">??????????????

?$('#div,#input').keyup(function(event){
    console.log(event.keyCode);
});??????

Actually, the code triggers only for the input, can I handle it for the div?

其实代码只对输入触发,我可以为div处理吗?

回答by Prasenjit Kumar Nag

You can add a tabindexin that divto catch keyboard events like this

您可以tabindex在其中添加一个div来捕获这样的键盘事件

<div id="div" style="height:50px" class="ui-widget-content" tabindex="0"></div>

Like answeredhere.

就像在这里回答一样。

Working Fiddle

工作小提琴

Reference

参考

回答by Selvakumar Arumugam

Add a tabindexand it should work

添加一个tabindex它应该可以工作

<div id="div" style="height:50px;" class="ui-widget-content" tabindex="1"></div>

DEMO

演示

回答by mkoryak

you need to add a tabindex to the div.

您需要向 div 添加一个 tabindex。

see this fiddle:

看到这个小提琴:

http://jsfiddle.net/w2Y4d/1/

http://jsfiddle.net/w2Y4d/1/

回答by Brian Scott

Why not place the input inside the div and then simply find $('#input').closest('div') ?

为什么不将输入放在 div 内,然后简单地找到 $('#input').closest('div') ?

Otherwise, if your example is a pattern of how your inputs relate to your divs then simply $('#input').prev() ?

否则,如果您的示例是您的输入如何与您的 div 相关的模式,那么只需 $('#input').prev() ?