是否可以在textarea中插入文本并更新撤消/重做队列?

Cyr*_* N. 7 javascript textarea undo-redo

几天前,我发布了一个关于如何在Internet Explorer中更新文本的问题.如图所示,使用的方法在Firefox中也不起作用.

这让我想到是否有办法修改textarea的值并更新un​​do/redo队列(调用ctrl-Zdocument.execCommand('undo');)

到目前为止,我发现了两种可能性,但它们并不适用于所有浏览器:

选项1:

var event = document.createEvent('TextEvent');
event.initTextEvent('textInput', true, true, null, text, 9, "en-US");
textarea.focus();
textarea[0].setSelectionRange(selection.start, selection.end);
textarea[0].dispatchEvent(event);
Run Code Online (Sandbox Code Playgroud)

注意:似乎在IE(根本没有)和Firefox中都不起作用

选项2:

document.execCommand("insertText", false, "the text to insert");
Run Code Online (Sandbox Code Playgroud)

在IE中不起作用(在9下测试,但似乎根本没有实现),我不知道其他浏览器.

Cyr*_* N. 6

到目前为止我提出的解决方案就是这个,但我愿意接受更好的想法:

我通过document.queryCommandSupported检查insertText是否存在.如果确实存在,我会使用它.如果没有,我只需替换文字:

var text = "hello world",
    textarea = jQuery("textarea"),
    selection = {'start': textarea[0].selectionStart, 'end': textarea[0].selectionEnd};

if (document.queryCommandSupported('insertText')) {
    document.execCommand('insertText', false, text);
}
else {
    textarea.val(textarea.val().substring(0, selection.start) + text + textarea.val().substring(selection.end, textarea.val().length));
}
Run Code Online (Sandbox Code Playgroud)