getComputedStyle是一个不在dom中的克隆元素 [英] getComputedStyle of a clone element which is not in the dom
问题描述
我有一个html页面;
I have a html page like;
<div id="cloneDiv">
<h1>
<a href="">ASUS Vivotab Smart Black Office 2013 H&S ME400C-C2-BK 10.1-Inch 64GB Tablet
(Black)</a>
</h1>
<div id="fordBackgroundImage" style="display: inline-block; background-position: center center; width: 1200px;
height: 565px; background-image: url('http://www.ford.com/ngbs-services/resources/ford/edge/2013/npcolorizer/edg13_ingotsilver.jpg');
background-repeat: no-repeat; background-attachment: scroll; position: relative;">
<div style="position: absolute; color: white; font-weight: bold; top: 50px; left: 100px; font-size: 50px;">
Try new ford jeep!
</div>
</div>
<p>
<img alt="" src="http://ecx.images-amazon.com/images/I/81UsKLK%2B6LL._SX342_.jpg"
class="border thumb0 selected" style="cursor: pointer;">
</p>
<p>
<img border="0" src="http://g-ecx.images-amazon.com/images/G/01/kindle/otter/dp/o1_slate_sm._V358729399_.jpg"
style="width: 320px; height: 282px;">
</p>
</div>
我有一个javascript函数将元素转换为计算样式元素;
and I have a javascript function to convert element to computed style element;
function MakeCssInline(elementParam) {
var domE = $(elementParam).get()[0];
var cssText = window.getComputedStyle(domE).cssText;
$(elementParam).attr("style", cssText);
// children
var items = domE.getElementsByTagName("*");
for (var i = 0; i < items.length; i++) {
var domE2 = items[i];
var cssText2 = window.getComputedStyle(domE2).cssText;
$(items[i]).attr("style", cssText2);
}
};
如果我在原始元素上调用函数,但它改变原始元素html
If I call function on original element it works; but it changes original element html
MakeCssInline($("#cloneDiv"));
但是当我尝试在克隆元素上调用此函数时,它不起作用;
But When I try to call this function on cloned element it does not work;
var cloneElement = $("#cloneDiv").clone();
MakeCssInline(cloneElement);
它不会对元素应用样式,因为我没有在body元素中追加,
因为我不想弄乱原始元素,有什么办法使用javascript来获取元素的计算样式克隆?
it does not apply styles to element because I did not append in the body element, since I do not want to mess with original element, is there any way to get computed style clone of an element with javascript?
推荐答案
我写了一个非常基本的函数,遵循Felix Kling的建议;
I wrote a very basic function that follows Felix Kling's suggestion;
function MakeCssInline(elementParam) {
var cloned = $(elementParam).clone();
$(cloned).find("script").remove();
$(cloned).find("link").remove();
$(cloned).find("iframe").remove();
//
var domE = $(elementParam).get()[0];
var domCloned = $(cloned).get()[0];
//
var cssText = window.getComputedStyle(domE).cssText;
$(cloned).attr("style", cssText);
// children
var items = domE.getElementsByTagName("*");
var itemsCloned = domCloned.getElementsByTagName("*");
for (var i = 0; i < items.length; i++) {
var domE2 = items[i];
var cssText2 = window.getComputedStyle(domE2).cssText;
$(itemsCloned[i]).attr("style", cssText2);
}
return domCloned;
};
这篇关于getComputedStyle是一个不在dom中的克隆元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!