且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在光标所在位置插入一些文本?

更新时间:2022-12-30 13:19:09

在文本区域或文本输入中的光标处,这是你看起来有什么。它适用于所有主要的浏览器:

Here's a function to insert text at the cursor in a textarea or text input, which is what it seems you have. It works in all major browsers:

function insertTextAtCursor(el, text) {
    var val = el.value, endIndex, range, doc = el.ownerDocument;
    if (typeof el.selectionStart == "number"
            && typeof el.selectionEnd == "number") {
        endIndex = el.selectionEnd;
        el.value = val.slice(0, endIndex) + text + val.slice(endIndex);
        el.selectionStart = el.selectionEnd = endIndex + text.length;
    } else if (doc.selection != "undefined" && doc.selection.createRange) {
        el.focus();
        range = doc.selection.createRange();
        range.collapse(false);
        range.text = text;
        range.select();
    }
}

您可以使用它如下:

var iframeWin = document.getElementById('text').contentWindow;
var textObj = iframeWin.document.getElementById('Content');

insertTextAtCursor(textObj, "foo");