Javascript textarea undo redo [英] Javascript textarea undo redo
问题描述
有一个工具栏用于处理textarea中的文本。 (例如用一些模板围绕选定的文本)
我想知道是否有一种简单的方法来实现这一点,目前在使用系统undo / redo时,它会混淆(我认为系统只跟踪编辑之间的增量)。
您可以模拟 textInput
事件来操作textarea的内容。这种方式的变化是撤销/重做,我认为(我知道他们是在Safari)尊重$ / b>
var element = document .getElementById( 'someTextarea');
var text ='这个文本将被插入到textarea中';
var event = document.createEvent('TextEvent');
event.initTextEvent('textInput',true,true,null,text);
element.dispatchEvent(event); //在textarea上触发事件
基本上,插入文本就好像你自己粘贴了一样。所以如果选择了某个东西,它会被替换为文本。如果没有选择,文本将插入插入符的位置。撤销/重做应该能够正常工作(一次性撤消/重做整个插入的字符串),因为浏览器就像你自己键入/粘贴一样。
因为我说,我知道这是一个在Safari中用撤销/重做的魅力,所以我认为它也适用于Chrome。
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).
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)
var element = document.getElementById('someTextarea');
var text = 'This text will be inserted in the textarea';
var event = document.createEvent('TextEvent');
event.initTextEvent('textInput', true, true, null, text);
element.dispatchEvent(event); // fire the event on the the textarea
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.
这篇关于Javascript textarea undo redo的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!