使用JavaScript在文本区域中选定文本前后插入文本

6

如何使用JavaScript在textarea中选择文本前后插入文本?

选择发生在HTML表单的textarea字段中。


你需要广泛的浏览器支持还是现代浏览器就可以了(换句话说,至少要等到IE 9发布后再考虑)? - Hemlock
2个回答

7

这里是一个简单的脚本,适用于Internet Explorer、Firefox和Chrome浏览器,其中myField是一个对象引用。这个脚本是通过在网上找到的几个脚本组装而成的。

function insertAtCursor(myField, myValueBefore, myValueAfter) {

    if (document.selection) {

        myField.focus();
        document.selection.createRange().text = myValueBefore + document.selection.createRange().text + myValueAfter;

    } else if (myField.selectionStart || myField.selectionStart == '0') {

        var startPos = myField.selectionStart;
        var endPos = myField.selectionEnd;
        myField.value = myField.value.substring(0, startPos) + myValueBefore + myField.value.substring(startPos, endPos) + myValueAfter + myField.value.substring(endPos, myField.value.length);
    }
}

1
然而,当完成时,它不会将光标放置在闭合标记之后。 - Frug
对于那些想要将光标聚焦在文本区域内的人,可以在结尾的“if else”条件语句中插入以下代码:myField.focus(); myField.selectionStart = startPos + myValueBefore.length; myField.selectionEnd = endPos + myValueBefore.length; - skaveesh

6
尝试以下操作:
var selectionText = yourTextarea.value.substr(yourTextarea.selectionStart, yourTextarea.selectionEnd);
yourTextarea.value = "Text before" + selectionText + "Text after";

如果你想进行搜索和替换,那么以下代码可以完成此操作(在非Internet Explorer浏览器中):
var textBeforeSelection = yourTextarea.value.substr(0, yourTextarea.selectionStart);
var textAfterSelection = yourTextarea.value.substr(yourTextarea.selectionEnd, yourTextarea.value.length);
yourTextarea.value = textBeforeSelection + " new selection text " + textAfterSelection;

如果您想要支持IE浏览器,您需要做其他的事情。 - Hemlock
1
我认为上面的示例将替换整个文本区域内容...也许有一种搜索和替换的方法? - Riccardo
如果你想要搜索和替换,那么你可以读取文本直到选择的部分,然后再读取直到结尾的部分。我将编辑上面的答案,以便向你展示我的意思。 - Matschie
@Riccardo:不,jQuery不能处理这个,尽管有一些可以的jQuery插件。 - Tim Down

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接