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

Is it possible to insert text in textarea and update undo/redo queue?

本文关键字:更新 撤消 队列 重做 插入文本 文本 区域 是否      更新时间:2023-09-26
几天

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

这让我想到是否有办法修改文本区域的值并更新撤消/重做队列(调用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下测试,但似乎根本没有实现),我不知道其他浏览器。

到目前为止,我提出的解决方案是这个,但我对更好的想法持开放态度:

我通过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 目前运行良好(2016 年 8 月 19 日),但在即将发布的一个版本中在 Chrome 中已弃用。调度事件会生成以下警告:

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

似乎截至

今天,所有现代浏览器都支持您的选项#1,dispatchEvent。在此处查看更多内容:

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

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

尝试插入文本文本区域以包装此页面上的一些解决方案,以获得现代浏览器支持。如果您需要 IE8+ 支持,请尝试在光标处插入文本包。