禁用对Textarea或键盘输入的关注的最佳方法是什么?

时间:2020-09-24 06:08:11

标签: javascript html jquery textarea keydown

我希望用户能够使用文本区域并通过按下键盘来控制文本区域。当textarea专注于/正在使用时,似乎与按键按下的检测存在冲突。有什么好的解决方法吗?

伪代码:

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

1 个答案:

答案 0 :(得分:0)

我想你想要这样的东西。

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>