如何在设置值后在HTML textarea中进行撤消工作?

at.*_*at. 11 html javascript html5 textarea preventdefault

我有一个<textarea>元素,我听从某些按键.就像用户键入Tab键一样,我会阻止更改焦点的默认操作,并将制表符添加到正确的位置.

问题是当用户按下我收听的其中一个键时,撤消会变得有点乱.如何使撤消/重做功能起作用?我想要听ctrl/cmd-z和ctrl/cmd-shift-z按键,记录所有内容,并处理undos/redos,但编辑和上下文菜单选项不起作用......

您可以通过键入带有选项卡的字母进入,然后输入然后尝试撤消和重做:

const textarea = document.querySelector('textarea')
textarea.addEventListener('keydown', function (event) {
  if (event.key == "Tab") {
    event.preventDefault()
    const cursor = textarea.selectionStart
    textarea.value = textarea.value.slice(0, cursor) + '\t' + textarea.value.slice(textarea.selectionEnd)
    textarea.selectionStart = textarea.selectionEnd = cursor + 1
  } else if (event.key == "Enter") {
    event.preventDefault()
    const cursor = textarea.selectionStart
    textarea.value = textarea.value.slice(0, cursor) + '\n' + textarea.value.slice(textarea.selectionEnd)
    textarea.selectionStart = textarea.selectionEnd = cursor + 1
  }
})
Run Code Online (Sandbox Code Playgroud)
<textarea cols="50" rows="20"></textarea>
Run Code Online (Sandbox Code Playgroud)

小智 6

我认为问题的核心是Javascript和浏览器的默认撤消方法之间缺乏交互。使用Javascript将文本附加到文本区域不会以任何方式告诉浏览器的“撤消”删除附加的文本,因为浏览器的“撤消”仅是为了删除用户输入的文本,而不是文本的Javascript输入。

以您的代码为例。按下Enter键后,您告诉eventListener阻止preventDefault,这将阻止Enter键将用户输入附加到文本区域。然后,您可以使用Javascript来合成输入,而浏览器的“撤消”操作不会对其进行跟踪。

您可以使用Document.execCommand()来克服这种缺乏交互的情况。您可以通过链接检查它对浏览器的支持。

const textarea = document.querySelector('textarea');
textarea.addEventListener('keydown', function (event) {
    const cursor = textarea.selectionStart;
    if(event.key == "Tab"){
        event.preventDefault();
        document.execCommand("insertText", false, '\t');//appends a tab and makes the browser's default undo/redo aware and automatically moves cursor
    } else if (event.key == "Enter") {
        event.preventDefault();
        document.execCommand("insertText", false, '\n');
    }

});
Run Code Online (Sandbox Code Playgroud)

  • 如果 Stackoverflow 在他们的编辑器中有 `Tab` 部分,那就太棒了! (4认同)
  • 根据 MDN,“execCommand()”现已弃用。来自 [W3C 草案](https://w3c.github.io/editing/docs/execCommand/):*“此规范不完整,预计不会超越草案状态”*(根据 Git,自 2015 年 8 月 7 日以来就是这种情况。)话虽如此,这里有一个相关问题没有出现在“相关”侧栏中:/sf/ask/951790521/ (3认同)