Javascript 如何在 contenteditable 元素中用 html 替换选定的文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6251937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:57:24  来源:igfitidea点击:

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

javascriptjquerycontenteditable

提问by Frodik

With a contenteditable element how can I replace the selected content with my own html?

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

回答by NakedBrunch

See here for working jsFiddle: http://jsfiddle.net/dKaJ3/2/

在这里查看工作 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);
}

Code taken from Tim Down: Return HTML from a user-selected text

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

回答by Tim Down

To get the selected HTML, you can use the function I wrote for this question. To replace the selection with your own HTML, you can use this function. Here's a version of the replacer function that inserts an HTML string instead of a DOM node:

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

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>");