2014-12-03 37 views
2

我一直在争取相当一段时间的这个问题,并已(仍然)无法打印我的div的样式。无法插入样式表/脚本到window.open

目前,我的脚本是:

$('#printMeButton').click(function() { 
    //alert("a"); 
    var data = document.getElementById('thisPrintableTable').outerHTML; 

    var mywindow = window.open('', data); 
    mywindow.document.write('<html><head><title>Print Me!!!</title>'); 
    // mywindow.document.write('<link rel="stylesheet" type="text/css" href="Site.css" media="screen">'); 
    mywindow.document.write('</head><body>'); 
    mywindow.document.write(data); 
    mywindow.document.write('</body></html>'); 

    mywindow.document.close(); 
    mywindow.focus(); 
    mywindow.print(); 
    mywindow.close(); 
    return true; 

}); 

其嵌套在$(document).ready函数中。

当我包含所需的样式表(当前注释掉)时,打印预览中不显示任何内容。

我也有一些脚本对表的外观有影响,因此,我相信这可能会把这些包含到弹出窗口中的关键。

我该如何将这个包含到新的弹出窗口中?

有人可以请建议一种打印方式,因为它的立场?

编辑历史

  • </head><body>
  • 改变var data末除去了空间有outerHTML代替innerHTML
  • 改变的问题/从更好地了解问题
  • 的细节

回答

3

尝试打开使用window.open与CSS中认为这与本地HTML文件。并使用js将内容html设置为打印到本地html文件。

这里是要打印的页面: -

<html> 
<head> 
    <title></title> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
    <link href="test.css" rel="stylesheet" type="text/css" /> 
    <script src="jquery.js"></script> 
</head> 
<body> 
    <div id="print"> 
     <div class="red">TODO write content</div> 
    </div> 
    <button id="print_btn">Print</button> 
    <script> 
     $('#print_btn').click(function(){ 
      var newWindow = window.open('print.html','_blank'); 
      $(newWindow).load(function(){ 
       $(newWindow.document).find('body').html($('#print').html()); 
      }); 
     }) 
    </script> 
</body> 
</html> 

CSS文件test.css这里联系在一起的,我在window.open时打开print.html的test.css在print.html也与现在

,在print.html我会写: -

<html> 
<head> 
    <title></title> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
    <link href="test.css" rel="stylesheet" type="text/css" /> 
</head> 
<body> 

</body> 
</html> 
+0

你能否扩展/详细说明这一点?我有点理解这种可能性,但不是执行 – jbutler483 2014-12-03 10:42:58

+0

我已经添加了一些代码。现在检查它。 – Indra 2014-12-03 12:46:40

3

由于您提供了一个空字符串作为新窗口的URL(open函数的第一个参数),其中的页面很可能无法弄清楚样式表的位置(因为它的地址是“相对于空白“)。尝试指定样式表的绝对URL。

此外,还有media="screen"的属性,应改为media="print"

mywindow.document.write('<link rel="stylesheet" type="text/css" href="http://my.site/Site.css" media="print"') 
+0

这并没有工作我afraid.Still版画只是作为普通,因为它是 – jbutler483 2014-12-03 10:15:43

+0

前我刚刚编辑了答案 - 还有一个我媒体属性。 – 2014-12-03 10:19:29

+0

同样的结果:( – jbutler483 2014-12-03 10:20:34