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

时间:2013-11-06 14:18:09

标签: javascript textarea undo-redo

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

这使我想到是否有办法修改textarea的值并更新撤消/重做队列(调用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);

注意:IE(根本没有)和Firefox

似乎不起作用

选项2:

document.execCommand("insertText", false, "the text to insert");

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

4 个答案:

答案 0 :(得分: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));
}

答案 1 :(得分:2)

选项1截至目前(2016年8月19日)运行良好,但在Chrome即将推出的其中一个版本中已弃用。调度事件会生成以下警告:

  

从JavaScript生成的DOM事件触发了浏览器内的默认操作。此行为是非标准行为,将于2016年9月左右在M53中删除。有关详细信息,请参阅https://www.chromestatus.com/features/5718803933560832

答案 2 :(得分:0)

似乎截至今天,所有现代浏览器都支持您的选项#1,dispatchEvent。点击此处了解更多信息:

http://help.dottoro.com/ljrinokx.php

答案 3 :(得分:0)

只有支持document.execCommand("insertText")的浏览器才支持undo(目前:Chrome,Safari,Opera)。其他浏览器具有多种插入文本的方式,但不支持undo

请尝试insert-text-textarea在此页面上包装一些解决方案,以支持现代浏览器。如果需要IE8 +支持,请尝试使用insert-text-at-cursor软件包。