gpt4 book ai didi

javascript - 将键盘事件与文本区域一起使用

转载 作者:行者123 更新时间:2023-11-29 18:38:27 26 4
gpt4 key购买 nike

我正在使用文本区域制作一个基本的在线编辑器,我希望编辑器能够监听按键事件。我试图让代码监听按下的 tab 键,然后在文本内容之间添加空格(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>

最佳答案

这里有几个问题:

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

  2. 你正在做 .value += ' ' ,它将执行此操作:

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

  4. 你的 scripthead ,很难修复#3。通常,任何非 async , 非 defer , 非模块脚本应该在 body 的末尾,就在收盘前</body>标签。

  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。

关于javascript - 将键盘事件与文本区域一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58935482/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com