添加父窗口'使用javascript将CSS转换为子窗口

Adding parent window's CSS to child window using javascript

本文关键字:窗口 CSS 转换 javascript 使用 添加      更新时间:2023-09-26

我试图用主窗口的一小部分的可打印版本生成一个弹出窗口。我使用Meteor,所以HTML和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指的是父文档的头,而不是子文档。我不确定这是我遇到的安全问题,还是只是代码中有错误。

你知道我做错了什么吗?

我在我的一个页面上做了一件非常类似的事情。我只是使用"父"页来编写所有内容,它运行良好。以下是它对我的作用。看看这把小提琴在演奏。您会注意到,它只打印printMe分区中的内容。此外,打印的页面具有与父页面完全相同的脚本和样式。

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页面确实正在正确地转移到新的弹出窗口。

最终对我起作用的是用childDoc.write(myHtml); 在身体上添加一些东西

在此之前,CSS不会加载,但一旦我真正传入了几个div,CSS就显示出来了,没有任何其他修改。