使用javascript在textarea中选择之前和之后插入文本

Ric*_*rdo 5 javascript

如何使用javascript在textarea中选择之前和之后插入文本?选择发生在HTML表单的textarea字段中

Mat*_*hie 6

请尝试以下方法:

var selectionText = yourTextarea.value.substr(yourTextarea.selectionStart, yourTextarea.selectionEnd);
yourTextarea.value = "Text before" + selectionText + "Text after";
Run Code Online (Sandbox Code Playgroud)

如果你想搜索+替换,那么以下代码将成功(在非IE浏览器中)

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;
Run Code Online (Sandbox Code Playgroud)


小智 6

简单的脚本,适用于IE,MFF和GC,其中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);

    } 
}
Run Code Online (Sandbox Code Playgroud)