如何在contenteditable元素中用html替换所选文本

How to replace selected text with html in a contenteditable element?

本文关键字:替换 html 文本 contenteditable 元素      更新时间:2023-09-26

使用contenteditable元素,如何用自己的html替换所选内容?

请参阅此处了解如何使用jsFiddle:http://jsfiddle.net/dKaJ3/2/

function getSelectionHtml() {
    var html = "";
    if (typeof window.getSelection != "undefined") {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var container = document.createElement("div");
            for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                container.appendChild(sel.getRangeAt(i).cloneContents());
            }
            html = container.innerHTML;
        }
    } else if (typeof document.selection != "undefined") {
        if (document.selection.type == "Text") {
            html = document.selection.createRange().htmlText;
        }
    }
    alert(html);
}

来自Tim Down的代码:从用户选择的文本返回HTML

要获得所选的HTML,可以使用我为这个问题编写的函数。要用您自己的HTML替换所选内容,您可以使用此功能。以下是replacer函数的一个版本,它插入HTML字符串而不是DOM节点:

function replaceSelectionWithHtml(html) {
    var range;
    if (window.getSelection && window.getSelection().getRangeAt) {
        range = window.getSelection().getRangeAt(0);
        range.deleteContents();
        var div = document.createElement("div");
        div.innerHTML = html;
        var frag = document.createDocumentFragment(), child;
        while ( (child = div.firstChild) ) {
            frag.appendChild(child);
        }
        range.insertNode(frag);
    } else if (document.selection && document.selection.createRange) {
        range = document.selection.createRange();
        range.pasteHTML(html);
    }
}
replaceSelectionWithHtml("<b>REPLACEMENT HTML</b>");