简体   繁体   English

打印时无法将css文件添加到html

[英]not able to add the css file to html while print

I'm trying to add the css file to the HTML content while printing it. 我正在尝试在打印时将css文件添加到HTML内容。 But the css file is not getting added. 但是没有添加css文件。 I'm getting the output without the CSS. 我得到的输出没有CSS。 Can anyone please help me... 谁能帮帮我吗...

Here is my code 这是我的代码

 <html> <head> <script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.1.min.js" > </script> <script type="text/javascript"> function PrintElem(elem) { Popup($(elem).html()); } function Popup(data) { var mywindow = window.open('', 'mydiv', 'height=700,width=1200'); mywindow.document.write('<html><head><title></title>'); mywindow.document.write('<link rel="stylesheet" href="print.css" type="text/css" media="print"/>'); mywindow.document.write('</head><body >'); mywindow.document.write(data); mywindow.document.write('</body></html>'); mywindow.document.close(); // necessary for IE >= 10 mywindow.focus(); // necessary for IE >= 10 mywindow.print(); mywindow.close(); return true; } </script> </head> <body> <div id="mydiv"> This will be printed. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque a quam at nibh adipiscing interdum. Nulla vitae accumsan ante. </div> <div> This will not be printed. </div> <div id="anotherdiv"> Nor will this. </div> <input type="button" value="Print Div" onclick="PrintElem('#mydiv')" /> </body> </html> 

and this is my CSS file 'print.css' 这是我的CSS文件“ print.css”

 @media print { #mydiv { border: 10px solid !important; color: red; font-size:20px !important; } } 

Figured out where you are making problem: 找出问题所在:

  1. You are passing element 'mydiv' to function PrintElem. 您正在将元素“ mydiv”传递给功能PrintElem。
  2. PrintElem function is fetching only inner html and not complete div PrintElem函数仅获取内部html 而不完整div
  3. you are sending it to another function Popup (only innerhtml of mydiv) 您将其发送到另一个函数Popup(仅mydiv的innerhtml)
  4. Popup is opening new page with some html, css and js 弹出窗口使用html,css和js打开新页面
  5. in data variable you only get text and not DIV 'mydiv', which was actually needded instead of inner html only. 在数据变量中,您只会获得文本,而不会获得DIV'mydiv',而实际上是针刺的,而不是仅内部html。
  6. So when your page loads it do not find mydiv where you are applying css on. 因此,在页面加载时,找不到要在其上应用CSS的mydiv。

Solution please pass entire div rather then just div.html() into Popup funciton 解决方案,请将整个div而不是仅将div.html()传递到Popup函数中

try something like this or try other way to do so 尝试类似的方法或尝试其他方法

 function PrintElem(elem)
 {
    Popup($(elem)); // send div not html only
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM