2014-03-26 31 views
1

我使用此代码获取html元素以打印出我的表格。如何使用Javascript将CSS添加到新窗口?

<script type="text/javascript"> 


    function printPage(){ 
      var width = screen.width - 50; 
      var tableData = '<table width="'+width+'" border="1">'+document.getElementsByTagName('table')[0].innerHTML+'</table>'; 
      var data = '<button onclick="window.print()">Print this page</button>'+tableData;  
      myWindow=window.open('','','width=auto,height=auto'); 
      myWindow.innerWidth = screen.width; 
      myWindow.innerHeight = screen.height; 
      myWindow.screenX = 0; 
      myWindow.screenY = 0; 
      myWindow.document.write(data); 
      myWindow.focus(); 
     }; 
</script> 

但是,我有一个问题。

我的CSS样式没有出现在打印预览中。

我该如何在我的HTML代码中获取我的CSS元素? NB:我使用class来获取样式值的CSS样式。

+0

其CSS样式犯规出现在哪里? jsfiddle在哪里? HTML? CSS –

回答

4

尝试添加一个链接到您的css文件。

function printPage(){ 
     var width = screen.width - 50; 
     var tableData = '<table width="'+width+'" border="1">'+document.getElementsByTagName('table')[0].innerHTML+'</table>'; 

     var cssHead = '<head><link rel="stylesheet" type="text/css" href="mystyle.css"></head>' 

     var data = cssHead + '<button onclick="window.print()">Print this page</button>'+tableData;  
     myWindow=window.open('','','width=auto,height=auto'); 
     myWindow.innerWidth = screen.width; 
     myWindow.innerHeight = screen.height; 
     myWindow.screenX = 0; 
     myWindow.screenY = 0; 
     myWindow.document.write(data); 
     myWindow.focus(); 
    }; 

相关问题