捕获 DIV 元素上的按键(或按键)事件 [英] Capture key press (or keydown) event on DIV element

查看:94
本文介绍了捕获 DIV 元素上的按键(或按键)事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 DIV 元素上捕获按键或按键事件(使用 jQuery)?

需要什么才能使 DIV 元素获得焦点?

解决方案

(1)设置tabindex属性:

(2) 绑定到keydown:

 $('#mydiv').on('keydown', function(event) {//console.log(event.keyCode);开关(事件.keyCode){//....您对密钥的操作.....}});

设置焦点开始:

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

要删除 - 如果您不喜欢它 - div 焦点边框,请在 CSS 中设置 outline: none.

查看keycodes表了解更多keyCode可能性.

所有代码都假设您使用 jQuery.

#

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) 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.

#

这篇关于捕获 DIV 元素上的按键(或按键)事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆