Insert text in Javascript contenteditable div

后端 未结 4 1663
别跟我提以往
别跟我提以往 2020-12-29 12:24

I have a problem where I need to insert a text (string, may or may not have html tags) to a div. It has to be a div and not a textarea.

Is there anyway to do that? F

4条回答
  •  醉梦人生
    2020-12-29 13:10

    Here's a cross-browser example, adapted from this answer to work with iframes.

    function pasteHtmlAtCaret(html, selectPastedContent, iframe) {
        var sel, range;
        var win = iframe ? iframe.contentWindow : window;
        var doc = win.document;
        if (win.getSelection) {
            // IE9 and non-IE
            sel = win.getSelection();
            if (sel.getRangeAt && sel.rangeCount) {
                range = sel.getRangeAt(0);
                range.deleteContents();
    
                // Range.createContextualFragment() would be useful here but is
                // only relatively recently standardized and is not supported in
                // some browsers (IE9, for one)
                var el = doc.createElement("div");
                el.innerHTML = html;
                var frag = doc.createDocumentFragment(), node, lastNode;
                while ( (node = el.firstChild) ) {
                    lastNode = frag.appendChild(node);
                }
                var firstNode = frag.firstChild;
                range.insertNode(frag);
    
                // Preserve the selection
                if (lastNode) {
                    range = range.cloneRange();
                    range.setStartAfter(lastNode);
                    if (selectPastedContent) {
                        range.setStartBefore(firstNode);
                    } else {
                        range.collapse(true);
                    }
                    sel.removeAllRanges();
                    sel.addRange(range);
                }
            }
        } else if ( (sel = doc.selection) && sel.type != "Control") {
            // IE < 9
            var originalRange = sel.createRange();
            originalRange.collapse(true);
            sel.createRange().pasteHTML(html);
            if (selectPastedContent) {
                range = sel.createRange();
                range.setEndPoint("StartToStart", originalRange);
                range.select();
            }
        }
    }
    

提交回复
热议问题