3

我有一个像这样的html页面;

<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 函数将元素转换为计算的样式元素;

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

MakeCssInline($("#cloneDiv"));

但是当我尝试在克隆元素上调用此函数时,它不起作用;

var cloneElement = $("#cloneDiv").clone();
MakeCssInline(cloneElement);

它不会将样式应用于元素,因为我没有在 body 元素中附加,因为我不想弄乱原始元素,有没有办法使用 javascript 获取元素的计算样式克隆?

4

2 回答 2

4

我按照 Felix Kling 的建议编写了一个非常基本的函数;

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;
};
于 2013-09-09T20:46:39.133 回答
1

尝试将元素附加到正文,隐藏,撕掉您需要的信息,然后将其从 DOM 中删除。

于 2013-09-09T20:50:15.950 回答