【问题标题】:What is the best way to disable focus on a Textarea or Input on a keydown?禁用对文本区域或按键输入的焦点的最佳方法是什么?
【发布时间】:2020-09-24 06:08:11
【问题描述】:

我希望用户能够使用 textarea 并通过 keydown 控制 textarea。当 textarea 专注于/正在使用时,似乎与检测 keydown 存在冲突。有好的解决办法吗?

伪代码:

 keydown(function(event) {
    if (event.which == 11) {
        $(TextArea).focusout();
        SwitchTextAreaFunction();
        $(TextArea).focus();
      }
    }

【问题讨论】:

    标签: javascript html jquery textarea keydown


    【解决方案1】:

    我想你想要这样的东西。

    document.addEventListener('keydown', (e) => {
      const myTextArea = $("#myTextArea");
      if (e.keyCode === 13 /* 13=enter */ ) {
        if (!myTextArea.is(":focus")) {
          // textarea has no focus
          e.preventDefault();
          myTextArea.focus();
        } else {
          // textarea has focus
          myTextArea.blur();
        }
      }
    })
    <textarea id="myTextArea">TextArea</textarea>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-04
      • 2016-04-12
      • 1970-01-01
      相关资源
      最近更新 更多