【问题标题】:How to disable focus on pressing Tab rather than one input field using javascript如何使用javascript禁用对按Tab而不是一个输入字段的关注
【发布时间】:2019-11-24 02:21:34
【问题描述】:

基本问题是我在屏幕上有一个文本字段和一些按钮。 我不希望我的文本字段失去对任何按键/或鼠标点击的关注。 它对鼠标工作正常,但是当我按 TAB 时,它会将焦点切换到 URL,然后是按钮。我想禁用选项卡,否则它应该不惜一切代价将焦点从该输入字段移开。

【问题讨论】:

  • 请问您能告诉我们您当前的代码尝试吗?

标签: javascript tabs focus


【解决方案1】:

tab键禁用字段切换:

$('input').on('keydown', function(e) {
  if (e.keyCode == 9) {
    $(this).focus();
    e.preventDefault();
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <input type="text" id="field1">
  <input type="text" id="field2">
  <input type="text" id="field3">
  <input type="text" id="field4">
  <input type="button" value="Submit">
</form>

【讨论】:

    【解决方案2】:

    我已经更新了 MH2K9 的答案,因此它不需要 jQuery。

    const input = document.querySelector('input');
    input.addEventListener('keydown', handleKey, true);
    
    function handleKey(e) {
      if (e.key === 'Tab') {
        e.preventDefault();
        this.focus();
      }
    }
    &lt;input type="text" /&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-05
      • 2019-05-19
      • 2020-05-14
      • 2017-10-13
      • 2016-03-20
      相关资源
      最近更新 更多