开发者

Javascript set print stylesheet

开发者 https://www.devze.com 2023-02-18 21:17 出处:网络
How would I modify the style of an object for the print stylesheet? I\'m using jQuery, if that\'s of any help.

How would I modify the style of an object for the print stylesheet? I'm using jQuery, if that's of any help.

I basically want to set a css 开发者_Python百科property of an object, but have that property apply for print only, not screen. e.g. $('#myobject').css('background','white','print');


This question is a little vague, so I'm not sure if I'm following what you're trying to do. Are you trying to dynamically modify the style of an object for print?

If so, you can try adding styles to the head, like the following:

$('head').append('<style type="text/css" media="print">Whatever styles</style>');


You are going to need to add a CSSStyleSheet to document.styleSheets and set the media type to print. https://developer.mozilla.org/en/DOM/stylesheet


I think the only way to do this is set a special ID or class on the element, then define a style for that in your print stylesheet:

<html><head>
    <style type="text/css" media="print">
    .print_blue { color: blue; }
    </style>
</head><body>

<span id="to_change">This is black text.</span>
<a href="#" onclick="jQuery('#to_change').addClass('print_blue');return false">Click here</a>
to change it to blue for printing.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
</body></html>


Create a print css file in your application like this:

Filename: print.css

#myobject {
background-color: white;
}

In your application header, include the file like this:

<link rel="stylesheet" href="print.css" type="text/css" media="print" />

Note the media="print" when I included the stylesheet. This will apply your white background to the object only when printing.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号