【问题标题】:Tab Keydown event for HTML5 Date inputsHTML5 日期输入的 Tab Keydown 事件
【发布时间】:2014-02-10 07:43:27
【问题描述】:

我在捕获日期输入的 Tab Keydown 事件时遇到问题。假设我有一个包含五个输入的表单,其中第一个和最后一个是日期输入(这里的 html 供参考...我知道它缺少 ID、tabindex 等):

<form id="heyImAForm">
    <input type="date" id="in1" />
    <input type="text" id="notimportant2" />
    <input type="text" id="notimportant3" />
    <input type="text" id="notimportant4" />
    <input type="date" id="in5" />
</div>

我想做的是在用户 Shift-Tabs 退出第一个输入时调用一个方法,以及当用户 Tabs 退出最后一个输入时调用一个方法。

问题是,我想保留日期输入的本机 Tab 键行为,即在日/月/年之间移动。所以,是这样的:

$('#in1').keydown(function(e) {
    if (e.which == 9 && e.shiftKey) {
        doAThing();
    }
});
$('#in5').keydown(function(e) {
    if (e.which == 9) {
        doADifferentThing();
    }
});

....“有效”,但有效地杀死了本机 Tab 键行为。那么,长话短说,有没有办法只在焦点从日期输入移开时才触发 Tab 键事件,而不是在日/月/年之间移动?

【问题讨论】:

  • 我在这个答案上非常努力,所以如果您有任何问题,请告诉我它是怎么回事。

标签: javascript jquery html date input


【解决方案1】:

在尝试了一些事情之后,我认为最好的解决方案是您看到的 here,但请继续阅读以全面了解我在做什么。当用户在第一个元素上点击 shift-tab 或在第二个元素上点击不带 tab 的 shift 时,我们将设置 focusout。如果用户点击其他东西,我们必须取消绑定此操作,因此如果他们使用 shift-tab 键,我们不会触发该操作,而是停留在元素内然后移出它。所以尝试这样的事情:

$('#in1').keydown(function(e) {
  if (e.which == 9 && e.shiftKey) {
    $(document).mousedown(function(){
      $('#in1').unbind('focusout');
      $(document).unbind('mousedown');
    });
    $('#in1').focusout(function(){
      doAThing();
    });
  } else {
    $('#in1').unbind('focusout');
    $(document).unbind('mousedown');
  }
});
$('#in5').keydown(function(e) {
  if (e.which == 9 && !e.shiftKey) {
    $(document).mousedown(function(){
      $('#in5').unbind('focusout');
      $(document).unbind('mousedown');
    });
    $('#in5').focusout(function(){
      doADifferentThing();
    });
  } else {
    $('#in5').unbind('focusout');
    $(document).unbind('mousedown');
  }
});

您可以看到,当按下 shift-tab(in1) 或 tab-without-shift(in5) 时,我们也在设置整个文档的 mousedown。在mousedown 中,我们将解除focusout 的绑定,因此如果由于鼠标点击而离开焦点,我们不会触发doAThing()。我们还取消了文档上的mousedown 绑定,因为您不希望每次用户在这些元素上的 tabbing(in5) 或 shift-tabbing(in1) 之后单击时触发它。

您可能也有兴趣了解我在 this fiddle 上所做的事情。这不是最佳解决方案,因为 setTimeout 在许多情况下会导致一些问题和不良影响。

另外,在您提供的代码中,结束标记应为&lt;/form&gt; 而不是&lt;/div&gt;

【讨论】:

  • 正是我想要的。谢谢!
猜你喜欢
  • 2015-06-07
  • 2013-02-19
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 2015-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多