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

时间:2011-06-06 12:24:03

标签: javascript jquery contenteditable

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

2 个答案:

答案 0 :(得分:70)

请参阅此处了解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 DownReturn HTML from a user-selected text

答案 1 :(得分:48)

要获取所选的HTML,您可以使用我为this question编写的功能。要使用您自己的HTML替换选择,您可以使用this function。以下是替换器函数的一个版本,它插入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>");