Javascript 如何使用TextFormat信息复制HTML选择字符串

Javascript 如何使用TextFormat信息复制HTML选择字符串,javascript,html,selection,Javascript,Html,Selection,我已经看到了使用javascript复制HTML的答案。几乎所有的答案都使用了克隆内容,如下所示 function() { var html = ""; if (typeof window.getSelection != "undefined") { var sel = window.getSelection(); if (sel.rangeCount) { var container = document.createEl

我已经看到了使用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!=“未定义”){
var sel=window.getSelection();
如果(选择范围计数){
var container=document.createElement(“div”);
对于(变量i=0,len=sel.rangeCount;i

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

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

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;
}
function(){
var html=“”;
if(typeof window.getSelection!=“未定义”){
var sel=window.getSelection();
如果(选择范围计数){
var Node=sel.focusNode.parentNode.cloneNode(true);
//console.log(节点);
var container=document.createElement(“div”);
对于(变量i=0,len=sel.rangeCount;i
在我的测试中解释更多没有任何问题,或者举一些例子假设Hellohow you是编辑器中的文本。您试图仅从本文中复制“是”。我的要求是复制标签,也使用are。你想像这样被选中吗?你的父格式如何。。。这仅适用于单亲节点。如果我们对文本应用多种格式,并尝试复制相同的格式,则此逻辑将不起作用。