是否可以使用javascript编辑文本输入并将其添加到“撤消"堆栈中? [英] Is it possible to edit a text input with javascript and add to the Undo stack?

查看:46
本文介绍了是否可以使用javascript编辑文本输入并将其添加到“撤消"堆栈中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用javascript编辑 input textarea 的内容,并使用浏览器的撤消"命令撤消更改(例如 ctrl-Z )?

Is there a way to edit the contents of an input or textarea with javascript, and have that change be undo-able with the browser's "undo" command (eg ctrl-Z)?

我正在尝试将一个字符串(例如"Foo {0} bar")插入所选内容中的值,并且如果用户选择了一个范围,则将所选范围插入到字符串中,以代替"{0}".

I am trying to insert a string, such as "Foo {0} bar", into the value at the selection, and if the user has selected a range, the selected range is inserted into the string in place of the "{0}".

例如,如果文本区域包含"Example 1 2 3",并且光标位于"Example 1 | 2 3",则该函数会将值更改为"Example 1Foo blah bar 2 3"( valueIfNothingSelected 在这种情况下为"blah").如果选择范围"1 2",则该函数会将值更改为"Example Foo 1 2 bar 3".

For example if the textarea contains "Example 1 2 3" and the cursor is at "Example 1| 2 3", then the function would change the value to "Example 1Foo blah bar 2 3" (valueIfNothingSelected being "blah" in this case). If the range "1 2" was selected, the function would instead change the value to "Example Foo 1 2 bar 3".

在Chrome浏览器中,我对该功能进行了测试,它可以实现预期的功能,但是我无法通过 undo 撤消更改.

In Chrome I tested this function out, and it does what it is supposed to, but I cannot reverse the change with undo.

function insertTextAtCursor(text, valueIfNothingSelected) {
    var field = $('textarea[name="task_log_description"]')[0];
    var startPos = field.selectionStart;
    var endPos = field.selectionEnd;
    var processedText;
    if (startPos == endPos) {
        processedText = text.replace('{0}', valueIfNothingSelected);
        field.value = field.value.substring(0, startPos) + processedText + field.value.substring(endPos, field.value.length);
        field.selectionStart = startPos + text.indexOf('{0}');
        field.selectionEnd = field.selectionStart + valueIfNothingSelected.length;
    } else {
        var selectedText = field.value.substring(startPos, endPos);
        processedText = text.replace('{0}', selectedText);
        field.value = field.value.substring(0, startPos) + processedText + field.value.substring(endPos, field.value.length);
        field.selectionStart = startPos + text.indexOf('{0}');
        field.selectionEnd = field.selectionStart + selectedText.length;
    }
    field.focus();
}

推荐答案

我在 https://stackoverflow上找到了可以使用的解决方案.com/a/10345596/1021426

通过将"field.value = ..."行替换为:

By replacing the "field.value = ..." lines with:

document.execCommand("insertText", false, processedText);

...然后将"field.focus()"移至该行之前,我能够实现所需的撤消/重做功能.

...and moving "field.focus()" to before that line, I was able to achieve the undo/redo functionality I desired.

这篇关于是否可以使用javascript编辑文本输入并将其添加到“撤消"堆栈中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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