Javascript textarea 撤销重做 [英] Javascript textarea undo redo

查看:31
本文介绍了Javascript textarea 撤销重做的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个类似于 SO 上的小型 JavaScript 编辑器(用于 chrome 扩展).

I'm making a small javascript editor (for a chrome extension) somewhat like the one on SO.

有一个工具栏用于操作 textarea 中的文本.(例如,用一些模板包围所选文本)

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).

推荐答案

你或许可以模拟 textInput 事件来操作 textarea 的内容.我认为(我知道它们在 Safari 中)

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.

正如我所说,我知道这就像在 Safari 中使用撤消/重做的魅力一样,所以我认为它也适用于 Chrome.

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 撤销重做的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆