Javascript 文本区域撤消重做
我正在制作一个小型的 javascript 编辑器(用于 chrome 扩展),有点像 SO 上的编辑器。
有一个用于操作文本区域中的文本的工具栏。 (例如用一些模板包围选定的文本)
我想知道是否有一种简单的方法可以实现这一点,目前在使用系统撤消/重做时,它会弄乱文本(我认为系统只跟踪编辑之间的增量)。
I'm making a small javascript editor (for a chrome extension) somewhat like the one on SO.
There's a toolbar for manipulation of the text in the textarea. (e.g. surround the selected text with some template)
I was wondering if there is a easy way to achieve this, currently when using the system undo/redo, it messes the text up (I think the system is only keeping track of deltas between edits).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果文本区域具有焦点并且其插入符位于正确的位置,
将插入文本“要插入的文本”,保留浏览器的本机撤消堆栈。 (请参阅正在进行的工作HTML 编辑 API 规范 .)Chrome 18 支持此功能,但我不确定它引入的确切版本。
If the textarea has focus and its caret is at the correct position,
will insert the text "the text to insert", preserving the browser's native undo stack. (See the work in progress HTML Editing API spec.) Chrome 18 supports this, but I'm unsure of the exact version it was introduced.
您可以模拟
textInput
事件来操作文本区域的内容。我认为,以这种方式所做的更改会受到撤消/重做的尊重(我知道它们在 Safari 中)基本上,文本的插入就像您自己粘贴一样。因此,如果选择了某些内容,它将被文本替换。如果没有选择,文本将插入到插入符号的位置。撤消/重做应该正常工作(一次性撤消/重做整个插入的字符串),因为浏览器的行为就像您自己键入/粘贴一样。
正如我所说,我知道这就像 Safari 中撤消/重做的魅力一样,所以我认为它也适用于 Chrome。
You can probably simulate
textInput
events to manipulate the contents of the textarea. The changes made that way are respected by undo/redo, I think (I know they are in Safari)Basically, the text is inserted as though you pasted it yourself. So if something is selected, it'll be be replaced with the text. If there's no selection, the text will be inserted at the caret's position. And undo/redo should work normally (undoing/redoing the entire inserted string in one go), because the browser acts as if you typed/pasted it yourself.
As I said, I know this works like a charm with undo/redo in Safari, so I'd assume it works in Chrome as well.