How to print inline CSS styles?

送分小仙女□ 提交于 2019-12-04 19:02:01

问题


is there a way to print css styles, that are inline?

I use this code to print part of the code:

w=window.open();
w.document.write($('#printable').html());
w.print();
w.close();

I could use external file and make it media=print, but part of the html are chars, that are generated by php and I could make it by making class for every posible outcome, but that would be pain.

Any ideas? Thanks.


回答1:


See the Demo: http://jsfiddle.net/rathoreahsan/x69UY/

What do you think if you do like this:

<div id="printableDiv">
    <style type="text/css">
        @media print {
            #printable { 
               color: red; 
               // Any Other style you want to add 
             }
        }
    </style>
    <div id="printable">
        This Text will print in red color.
    </div>
</div>

Javascript/jQuery code:

w=window.open();
w.document.write($('#printableDiv').html());
w.print();
w.close();

In this scenario while a popup opens and gets the HTML of printableDiv, the styles for printer will be included in that popup so the printer will read styles from popup and will print in that manner.




回答2:


I had the same problem, because i use instyle style to dynamically change background-color, and then the color was not in the print. styleSheets[3] is my print.css file.

This worked for me: I uncluded it in the smarty foreach i use to give some elements a background color.

<script type='text/javascript'>
  document.styleSheets[3].insertRule(" #caldiv_<?smarty $item.calendar_id ?> { border-color:<?smarty $item.color ?> }", 1);
</script>


来源:https://stackoverflow.com/questions/7033340/how-to-print-inline-css-styles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!