【问题标题】:Using keyboard events with textareas使用带有文本区域的键盘事件
【发布时间】:2019-11-19 13:44:07
【问题描述】:

我正在使用文本区域制作一个基本的在线编辑器,我希望编辑器能够监听 keydown 事件。我试图让代码监听按下的 tab 键,然后在 textcontent 之间添加空格(4 个空格),但它不起作用。我该怎么办?

<!DOCTYPE html>
<html>

<head>
  <title>Editor</title>
  <link rel="stylesheet" href="stylesheet.css">
  <link rel="shortcut icon" href="">

  <script>
  document.addEventListener("keydown", logKey);

  function logKey(key){
    if (key.keyCode == "9"){
        myTextArea.textContent += '    ';
    }
  }
  </script>
</head>

<body>
<header>
  <div class="navBar" id="heading-container"></div>
</header>
  <textarea id="myTextArea">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent semper in nunc at mattis. Suspendisse metus augue, pellentesque finibus luctus dictum, tempor id nunc.
</body>
</html>

【问题讨论】:

  • 如果我没有在文本区域的结束按 Tab 怎么办?我强烈建议您不要尝试重新发明这个轮子。使用 CodeMirror 或类似的。
  • 尝试按键事件。
  • 你还需要取消操作

标签: javascript html css events textarea


【解决方案1】:

这里有几个问题:

  1. keyCode 是一个键代码,而不是一个字符,它是一个数字。对于 Tab 键,请使用 keyCode === 9。这是可靠的键码之一(并非所有键码都跨不同的键盘布局等)。

  2. 你正在做.value += ' ',它将这样做:

    • 从文本区域获取所有文本
    • ' ' 添加到它的末尾(无论用户按下Tab 时插入点在哪里)
    • 用更新后的字符串替换 textarea 中的所有文本,根据浏览器将插入点移动到开头或结尾
  3. 您正在document 上收听 Tab,而不仅仅是在文本区域内

  4. 您的 scripthead 中,因此很难修复 #3。通常,任何非async、非defer、非模块脚本都应位于body 的末尾,就在关闭&lt;/body&gt; 标记之前。

  5. 您依赖于myTextArea 的自动全局。尽管这些自动全局变量的创建现在已经标准化,但我强烈建议不要依赖它们。使用 DOM API 查找您需要的元素。

  6. 您可能希望阻止 Tab 按键的默认操作。

#2 尤其会造成相当糟糕的用户体验。

如果您真的想这样做,请阅读execCommand 了解#2。示例(也修复了其他提到的):

document.getElementById("myTextArea").addEventListener("keydown", handleKey); // #3, #5

function handleKey(event){
  if (event.keyCode === 9) { // #1
      document.execCommand("insertText", true, "    "); // #2
      event.preventDefault();                           // #6
  }
}
<textarea id="myTextArea" cols=30 rows=10>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent semper in nunc at mattis. Suspendisse metus augue, pellentesque finibus luctus dictum, tempor id nunc.</textarea>
<!--
Stack Snippets handle #4 for you, by putting
the script after the HTML
-->

但正如我在评论中所说,我强烈建议使用已经构建和测试过的东西,例如 CodeMirror。

【讨论】:

    【解决方案2】:

    将您的功能更改为以下给出的功能:

       if (key.keyCode == "9"){
           key.preventDefault();
           myTextArea.value += '    ';
       }
     }
    
    
    

    【讨论】:

      【解决方案3】:
           function logKey(key){
          if (key.keyCode == "9"){
              myTextArea.textContent += '    ';
              key.preventDefault();
          }
        }
      

      关闭标签是程序员的好习惯。 不要忘记关闭

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-09-01
        • 2011-08-29
        • 2017-08-30
        • 1970-01-01
        • 1970-01-01
        • 2015-09-11
        • 2014-07-14
        相关资源
        最近更新 更多