How can I use a 'keydown' event listener on a div?

半城伤御伤魂 提交于 2020-03-19 06:33:28

问题


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.

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.

Thank you!


回答1:


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.

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

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.

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
    }
});



回答2:


You can allow an element to receive focus by giving it a tab index.

<div tabindex="-1"></div>

As long as it's in focus key events should be captured on it.

If you want the element to be focusable using the Tab key, give it an index greater than -1.

Simple example



来源:https://stackoverflow.com/questions/51267273/how-can-i-use-a-keydown-event-listener-on-a-div

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