如何复制带有TextFormat信息的HTML选择字符串

How to Copy the HTML Selection String with TextFormat information

本文关键字:信息 TextFormat HTML 字符串 选择 何复制 复制      更新时间:2023-09-26

我看到了使用javascript复制HTML的答案。几乎所有的答案都是使用低于的克隆内容

function() {
    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;
        }
    }
    return html;
};

但在这里,如果标记在选择区域中,那么只有格式被复制,否则它将被复制为文本本身。我想复制与所选内容相关联的格式信息。我怎样才能做到这一点。

测试它可以使用父节点进行选择

function(){
 var html = "";
 if (typeof window.getSelection != "undefined") {
    var sel = window.getSelection();
    if (sel.rangeCount) {
        var Node=sel.focusNode.parentNode.cloneNode(true);
        //console.log(Node);
        var container = document.createElement("div");
        for (var i = 0, len = sel.rangeCount; i < len; ++i) {
            container.appendChild(sel.getRangeAt(i).cloneContents());
        }
        html = container.innerHTML;
        //
        Node.innerHTML=html;
        var co = document.createElement("div");
        co.appendChild(Node);
        html=co.innerHTML;
    }
 } else if (typeof document.selection != "undefined") {
    if (document.selection.type == "Text") {
        html = document.selection.createRange().htmlText;
    }
 }
 return html;
}