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();
    }
};
    原文作者:小弟调调
    原文地址: https://segmentfault.com/a/1190000002459526
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞