Insert an HTML element in a contentEditable element

前端 未结 2 899
我在风中等你
我在风中等你 2021-02-03 14:57

I have a contentEditable div where I want to insert HTML tags (a simple span element).

Is there a cross browser solution that allows me to insert those tags over my div

2条回答
  •  星月不相逢
    2021-02-03 15:33

    The following will do this in all major browsers (including IE 6). It will also handle cases where the end of the selection is outside your

    and cases where the selection is contained within a child (or more deeply nested) element inside the
    .

    2019 addendum: The second branch of insertNodeOverSelection is for IE <= 8 only and could be removed now.

    function isOrContainsNode(ancestor, descendant) {
        var node = descendant;
        while (node) {
            if (node === ancestor) return true;
            node = node.parentNode;
        }
        return false;
    }
    
    function insertNodeOverSelection(node, containerNode) {
        var sel, range, html;
        if (window.getSelection) {
            sel = window.getSelection();
            if (sel.getRangeAt && sel.rangeCount) {
                range = sel.getRangeAt(0);
                if (isOrContainsNode(containerNode, range.commonAncestorContainer)) {
                    range.deleteContents();
                    range.insertNode(node);
                } else {
                    containerNode.appendChild(node);
                }
            }
        } else if (document.selection && document.selection.createRange) {
            range = document.selection.createRange();
            if (isOrContainsNode(containerNode, range.parentElement())) {
                html = (node.nodeType == 3) ? node.data : node.outerHTML;
                range.pasteHTML(html);
            } else {
                containerNode.appendChild(node);
            }
        }
    }
    
    
    
    This is the editable element where the insertion will happen. Select something or place the cursor in here, then hit the button above
    No insertion will happen here

提交回复
热议问题