[英]How to make undo work in an HTML textarea after setting the value?
我有一个<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 } })
<textarea cols="50" rows="20"></textarea>
我认为问题的核心是Javascript与浏览器的默认撤消方法之间缺乏交互。 使用Javascript将文本附加到textarea并不以任何方式告诉浏览器“撤消”删除附加文本,因为浏览器的“撤消”仅用于删除用户输入的文本,而不是文本Javascript输入。
以你的代码为例。 在按Enter键时,告诉eventListener使用preventDefault,这会阻止Enter键将用户输入附加到textarea。 然后使用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');
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.