How can I get keydown events on a div in chrome?

2020-06-03 06:08发布

I'd like to get keydown events on a div. I use JQuery keydown. Pretty simple.

However, it does not work on chrome. For this to work on chrome, I have to set tabindex = 0.

If I do this, Chrome puts an ugly orange border around my div.

Is there a way to make this work on chrome without the ugly orange border?

1条回答
我欲成王,谁敢阻挡
2楼-- · 2020-06-03 07:03

Keydown event is only sent to the HTML element that has the focus. Focusable elements vary between browsers, but elements of which tabindex property is set can always get focus in most browsers.

You have already set tabindex for div element so that it is focusable and can receive keyboard event. Your problem is the default outline of currently focused element on Google Chrome.

To change the outline (the "ugly orange border" as you mentioned), use pseudo CSS class :focus and CSS property outline. The following example will remove outline from all elements when they have focus:

*:focus
{
    outline: none;
}

Hope this help.

查看更多
登录 后发表回答