几天前,我发布了一个关于如何在Internet Explorer中更新文本的问题。然而,这种方法似乎在Firefox中也无法使用。
这让我想到是否有一种方法可以修改textarea的值并更新撤销/重做队列(调用ctrl-Z
或document.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及以下版本测试过,但似乎根本没有实现),其他浏览器情况未知。