2013-02-15 178 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