如何在div上使用"keydown"事件侦听器? [英] How can I use a 'keydown' event listener on a div?

查看:555
本文介绍了如何在div上使用"keydown"事件侦听器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试捕获按键下降事件,其中特定的键对应于要播放的特定的音频片段.我一直在搜索,但很困惑.看来keydown事件仅在window/document对象中可用.这样对吗?我已经看过一些有关jQuery插件的话题,尽管我想远离jQuery.香草JS是理想的选择.

I am trying to capture keydown events where specific keys correspond to specific audio clips to be played. I've been searching but I am stumped. It seems that the keydown event is only available in the window/document object. Is this correct? Ive seen some talk of jQuery plugins, although i would like to stay away from jQuery. Vanilla JS is ideal.

我有2个DIVS,我想同时监听按键事件.根据按下的键,该功能将播放相应的音频剪辑.

I have 2 DIVS that I want to listen for keydown events on at the same time. Based on which keys are pressed, the function plays the corresponding audio clip.

谢谢!

推荐答案

div一个

Give the div a tabindex, so it will be focusable. In your case, a tabindex of -1 would be best as it would allow the element to be focused but remain unaccessible by the tab key.

tabindex全局属性指示其元素是否可以聚焦,以及是否/在何处参与顺序键盘导航(通常使用Tab键,因此使用名称).

The tabindex global attribute indicates if its element can be focused, and if/where it participates in sequential keyboard navigation (usually with the Tab key, hence the name).

负值(通常为tabindex =-1")表示该元素应该是可聚焦的,但不应通过顺序键盘导航来访问.使用JavaScript创建可访问的小部件最有用.

A negative value (usually tabindex="-1") means that the element should be focusable, but should not be reachable via sequential keyboard navigation. It's mostly useful to create accessible widgets with JavaScript.

然后可以将keydown事件侦听器添加到元素中,并检查事件的keyCode.

You can then add a keydown event listener to the element and check for the keyCode of the event.

document.getElementById("someId").addEventListener("keydown", function(event){
    //do something on keydown
    if(event.keyCode==13){
     //enter key was pressed
    }
    if (event.keyCode >= 65 && event.keyCode <= 90){
       //input was a-z
    }
});

这篇关于如何在div上使用"keydown"事件侦听器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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