IE下复制HTML5标签节点的问题及解决

在jQuery的源代码中,jQuery.support对于是否支持html5节点复点作了检测。

// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>"

原因在于在于低于IE8的浏览器(对的,又是IE这货),cloneNode()方法存在问题。
具体检测见此:司徒正美:检测是否为HTML5新标签

在manipulations源代码中给出了解决方法:

clone: function(elem, dataAndEvents, deepDataAndEvents) {
	var srcElements,
	var srcElements, destElements, i, clone;

	if (jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test("<" + elem.nodeName + ">")) {
		clone = elem.cloneNode(true);
		// IE<=8 does not properly clone detached, unknown element nodes
	} else {
		fragmentDiv.innerHTML = elem.outerHTML;
		fragmentDiv.removeChild(clone = fragmentDiv.firstChild);
	}
	//省略之后代码
}

下面是mass-Framework针对此作的解决方法:

var div = document.createElement( "div" );//缓存parser,防止反复创建
 function shimCloneNode( outerHTML, tree ) {
     tree.appendChild(div);
     div.innerHTML = outerHTML;
     tree.removeChild(div);
     return div.firstChild;
 }
 var unknownTag = "<?XML:NAMESPACE"
 function cloneNode( node, dataAndEvents, deepDataAndEvents ) {
     var bool //!undefined === true;
     //这个判定必须这么长:判定是否能克隆新标签,判定是否为元素节点, 判定是否为新标签
     if(!support.cloneHTML5 && node.outerHTML){//延迟创建检测元素
         var outerHTML = document.createElement(node.nodeName).outerHTML;
         bool = outerHTML.indexOf( unknownTag ) // !0 === true;
     }
     var neo = !bool? shimCloneNode( node.outerHTML, document.documentElement ): node.cloneNode(true), src, neos, i;
   //support.cloneHTML5: DOC.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>",
   //……
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>