0

我已经看到了使用 javascript 复制 HTML 的答案。几乎所有的答案都是使用 clonecontents 如下

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;
};

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

4

1 回答 1

0

测试它可以选择父节点

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;
}
于 2013-02-05T05:07:02.480 回答