简体   繁体   English

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

[英]Insert text before and after selection in textarea with javascript

How to insert text before and after selection in textarea with javascript? 如何使用javascript在textarea中选择之前和之后插入文本? Selection occurs into a textarea field of a HTML form 选择发生在HTML表单的textarea字段中

Simple script that works in both IE, MFF and GC where myField is a object reference. 适用于IE,MFF和GC的简单脚本,其中myField是对象引用。 Assembled by several scripts found through the web. 由通过网络找到的几个脚本组装而成。

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);

    } 
}

Try the following: 请尝试以下操作:

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

If you want to search + replace then the following code will do the trick (In non IE browsers) 如果要搜索+替换,则以下代码可以解决问题(在非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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM