js insertStr 在光标处插入字符串

在光标处插入字符串
obj文本框对象的id
str要插入的值

range

jsfunction insertStr(obj, str) {
    /*在光标处插入字符串 ,obj文本框对象的id ,str要插入的值*/
    ob = document.getElementById(obj) || obj;
    ob.focus();
    var selection = window.getSelection ? window.getSelection() : document.selection;
    var range = selection.createRange ? selection.createRange() : selection.getRangeAt(0);
    if (!window.getSelection) {
        range.innerText(str);
        range.collapse(false);
        range.select();
        ob.focus();
    } else {
        range.collapse(false);
        var hasR = range.createContextualFragment(str);
        var hasR_lastChild = hasR.lastChild;
        while (hasR_lastChild && hasR_lastChild.nodeName.toLowerCase() == "br" && hasR_lastChild.previousSibling && hasR_lastChild.previousSibling.nodeName.toLowerCase() == "br") {
            var e = hasR_lastChild;
            hasR_lastChild = hasR_lastChild.previousSibling;
            hasR.removeChild(e)
        }
        range.insertNode(hasR);
        if (hasR_lastChild) {
            range.setEndAfter(hasR_lastChild);
            range.setStartAfter(hasR_lastChild)
        }
        selection.removeAllRanges();
        selection.addRange(range)
        ob.focus();
    }
};

你可能感兴趣的:(javascript)