您不仅需要克隆,而且可能还需要进行深度克隆。
node.cloneNode(true);
文档是here。
如果 deep 设置为 false,则没有
子节点被克隆。任何文字
包含的节点未克隆
要么,因为它包含在一个或
更多子文本节点。
如果 deep 评估为真,则整个
子树(包括可能在
子文本节点)也被复制。为了
空节点(例如 IMG 和 INPUT
元素)是否无关紧要
deep 设置为 true 或 false 但您
仍然必须提供一个值。
编辑:OP 声明 node.cloneNode(true) 没有复制样式。下面是一个简单的测试,它使用 jQuery 和标准 DOM API 显示了相反的结果(以及预期的效果):
var node = $("#d1");
// Add some arbitrary styles
node.css("height", "100px");
node.css("border", "1px solid red");
// jQuery clone
$("body").append(node.clone(true));
// Standard DOM clone (use node[0] to get to actual DOM node)
$("body").append(node[0].cloneNode(true));
结果可见:http://jsbin.com/egice3/
编辑 2
希望你之前提到过;) 计算风格是完全不同的。更改您的 CSS 选择器或将该样式应用为一个类,您将获得解决方案。
编辑 3
因为这个问题是一个合法的问题,我没有找到任何好的解决方案,它让我很困扰,想出了以下问题。它不是特别优雅,但它可以完成工作(仅在 FF 3.5 中测试过)。
var realStyle = function(_elem, _style) {
var computedStyle;
if ( typeof _elem.currentStyle != 'undefined' ) {
computedStyle = _elem.currentStyle;
} else {
computedStyle = document.defaultView.getComputedStyle(_elem, null);
}
return _style ? computedStyle[_style] : computedStyle;
};
var copyComputedStyle = function(src, dest) {
var s = realStyle(src);
for ( var i in s ) {
// Do not use `hasOwnProperty`, nothing will get copied
if ( typeof s[i] == "string" && s[i] && i != "cssText" && !/\d/.test(i) ) {
// The try is for setter only properties
try {
dest.style[i] = s[i];
// `fontSize` comes before `font` If `font` is empty, `fontSize` gets
// overwritten. So make sure to reset this property. (hackyhackhack)
// Other properties may need similar treatment
if ( i == "font" ) {
dest.style.fontSize = s.fontSize;
}
} catch (e) {}
}
}
};
var element = document.getElementById('origin');
var copy = element.cloneNode(true);
var destination = document.getElementById('destination');
destination.appendChild(copy);
copyComputedStyle(element, copy);
有关更多信息和一些注意事项,请参阅 PPK 题为 Get Styles 的文章。