jquery - 为什么我的 DIV 在获得焦点时不捕获按键事件?

标签 jquery html events focus keypress

我正在使用 jQuery 1.12。我希望 DIV 在具有焦点时捕获按键(特别是向下和向上箭头)。所以我跟着这个

 $('div.select-styled').bind('keydown', function(event) {
    console.log(event.keyCode);
    elt = $(this).search(".select-options li:hover");
    console.log(elt);
    switch(event.keyCode){
    // case up
    case 38:
        console.log(“up pressed.”)
        break;
    case 40:
        console.log(“down pressed”)
        break;
    }
 });

但这不是捕获按键。在这里查看我的 fiddle — http://jsfiddle.net/cwzjL2uw/10/ .单击“Select State”菜单,或单击“Last Name”字段,然后单击“Tab”将焦点置于下一个 DIV。然而,当该菜单有焦点时,点击任何键都不会激活上面的处理程序,至少在 Mac Chrome 或 Firefox 上它不会激活。

感谢任何帮助,-

最佳答案

提供您的 .select-styled元素tabindex属性(例如:tabindex="1")将允许它接收 JavaScript 键盘事件。


解释: .keydown() 的 jQuery API提到它只适用于可聚焦的元素:

It can be attached to any element, but the event is only sent to the element that has the focus. Focusable elements can vary between browsers, but form elements can always get focus so are reasonable candidates for this event type.

根据这个previous Stack Overflow answer , <div>默认情况下元素不可聚焦,但 DOM Level 2 HTML指出除其他规则外,任何带有 tabindex 的元素可以接收焦点:

Today's browsers define focus() on HTMLElement, but an element won't actually take focus unless it's one of:

  • HTMLAnchorElement/HTMLAreaElement with an href
  • HTMLInputElement/HTMLSelectElement/HTMLTextAreaElement/HTMLButtonElement but not with disabled (IE actually gives you an error if you try), and file uploads have unusual behaviour for security reasons
  • HTMLIFrameElement (though focusing it doesn't do anything useful). Other embedding elements also, maybe, I haven't tested them all.
  • Any element with a tabindex

或者,这可能是更好的做法,您可以简单地绑定(bind)您的 keydown $(document) 的事件处理程序当元素收到 focus 时(你的 jQuery 已经毫无问题地处理了),并在 blur 上解除绑定(bind).

关于jquery - 为什么我的 DIV 在获得焦点时不捕获按键事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41421132/

相关文章:

c++ - 通用调度程序类

jquery - bootstrap datepicker js禁用 future 日期

javascript - 使用 jquery append 到特定的 id 和类

javascript - 如何使元素刷新后不可见

jquery - 在 Webkit 浏览器中悬停后的 CSS3 动画速度不正确

c - 用cudaEvent_t测CPU时间靠谱吗?

javascript - 如何隐藏文本字段中闪烁的光标

html - 模态中的日期选择器

html - 变换:旋转模糊图像

javascript - 动态创建的元素上的事件绑定(bind)?