js实现textarea中光标位置插入你想要插入的内容

 function insertAtCursor(myField, myValue)
    {
        //IE support
        if (document.selection)
        {
            myField.focus();
            sel            = document.selection.createRange();
            sel.text    = myValue;
            sel.select();
        }
        //MOZILLA/NETSCAPE support
        else if (myField.selectionStart || myField.selectionStart == '0')
        {
            var startPos    = myField.selectionStart;
            var endPos        = myField.selectionEnd;
            // save scrollTop before insert
            var restoreTop    = myField.scrollTop;
            myField.value    = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
            if (restoreTop > 0)
            {
                // restore previous scrollTop
                myField.scrollTop = restoreTop;
            }
            myField.focus();
            myField.selectionStart    = startPos + myValue.length;
            myField.selectionEnd    = startPos + myValue.length;
        } else {
            myField.value += myValue;
            myField.focus();
        }
    }

 

//说明myField表示textarea对象,myvalue表示要在光标闪烁处插入的字符串

举例使用说明:

var myFiledObj=docuement.getElementById("textAreaId");

var myStr="我想在这里插入我自己的字符串";

insertAtCursor(myFiledObj,myStr);

 

你可能感兴趣的:(js实现textarea中光标位置插入你想要插入的内容)