2013-02-15 180 views
2

我正嘗試使用主窗口的一小部分的可打印版本生成彈出窗口。我正在使用Meteor,所以HTML和CSS文件都是以編程方式生成的。使用javascript將父窗口的CSS添加到子窗口

我想要做的就是使用Javascript讀取父窗口中的所有鏈接CSS文件,並將它們附加到子窗口。

var childWindow = window.open("", "_blank", "width=350,height=150"); 
var childDoc = childWindow.document; 
var childHead = childDoc.getElementsByTagName("head")[0]; 

$('link').each(function(index,element){ 
    childLink = childDoc.createElement("link"); 
    childLink.rel = "stylesheet"; 
    childLink.href = element.href; 
    childHead.appendChild(childLink); 
}); 
childDoc.write(myHtml); 

但它不工作。看起來childHead是指母文件的頭,而不是孩子。我不確定這是否是我遇到的安全問題,或者只是在代碼中出現錯誤。

任何想法我做錯了什麼?

回答

0

什麼結束了工作對我來說是附加的東西對身體有childDoc.write(myHtml);

在此之前,在CSS不會加載,但一旦我在幾個div的實際傳遞,在CSS出現了沒有任何其他修改。

1

我在我的一個頁面上做了非常類似的事情。我只是使用'父'頁面來編寫一切,它工作正常。這是它對我的作用。見this fiddle在行動。 你會注意到它只打印printMe div的東西。此外,打印頁面具有與父頁面完全相同的完全相同的腳本和樣式。

some stuff NOT to print 
<div id="printMe" class="ui-selectable-helper"> 
    I should be printed, but not the other stuff. 
</div> 
more stuff NOT to print 

$(function(){ 
    var printWindow = window.open('', 'printWin', 'height=600, width=900, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, directories=no, status=no'); 

    //create a new HEAD with the exact same content as the main page 
    var writeMe = ('<body><head>' + $('head').html() + '</head><html>'); 

    //grab the content of the printMe div and use it on the print page 
    writeMe += ("<div>" + $('#printMe')[0].outerHTML + "</div>"); 
    writeMe += ('</html></body>');  
    printWindow.document.write(writeMe); 
    printWindow.document.close();  
    printWindow.focus(); 
    printWindow.print(); 

    //you might even use this next line if you want the 'popup' window to go away as soon as they have finished printing. 
    //printWindow.close(); 
}); 

注:我只是用class="ui-selectable-helper"告訴你,確實是CSS網頁已正確轉移到新的彈出窗口。

+0

其實,它只是出現在身體。至少這就是它在鉻中的方式。 – 2013-04-21 00:16:25