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

时间:2011-01-17 14:21:15

标签: javascript

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

2 个答案:

答案 0 :(得分: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);

    } 
}

答案 1 :(得分:5)

尝试以下方法:

var selectionText = yourTextarea.value.substr(yourTextarea.selectionStart, yourTextarea.selectionEnd);
yourTextarea.value = "Text before" + selectionText + "Text after";

如果你想搜索+替换,那么下面的代码就可以解决这个问题(在非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;