开发者

Use Javascript to Change Display Styles (CSS) Without Affecting Print Styles

I have a web application that utilizes a separate print stylesheet to control how the page looks when it comes out of the printer. That was working wonderfully until I recently made some Javascript enhancements to the site. One of these enhancements allows the user to freeze the page header and navigation, as well as table headers. The Javascript behind this does some CSS trickery to freeze the elements on the screen. Unfortunately, applying position: fixed to my hea开发者_如何学运维der (for example) causes it to print on every page, and this is not a desired effect. How can I use Javascript to tweak element styles on the client-side without affecting the print style?

@media print { #foo { color: blue; } }               /* Print definition */
@media screen { #foo { color: green; } }             /* Display definition */
document.getElementById('foo').style.color = 'red';  /* Overrides both! */


Instead of changing properties on your elements with this:

document.getElementById('foo').style.color = 'red'; 

append a new <style> element, for example:

$('<style>@media screen { #foo { color: green; } }</style>').appendTo('head');

It would be better to concatenate all your required changes into one <style> element, if possible.


Add !important to your print rules.


You can try this @media print { #foo { color: blue !important; } }

The problem is that javascript .style.something, edits the inline css of the element, therefore it will override the normal css class/id rules.

Or you can, work with classes. document.getElementById('foo').className = 'redText';

and keep the .redText in your regular css file (not the print one), much much better than filling your print css with !important rules.


No good solution! What I ended up doing is utilizing the onbeforeprint and onafterprint functions in IE (I am in the position here that we only have IE users) to "unfreeze" and "refreeze" the elements...

window.onbeforeprint = function() {
  document.getElementById('foo').style.position = 'static';
}

window.onload = window.onafterprint = function() {
  var el = document.getElementById('foo');
  // Get element position and size
  // Set left/top/width/height properties
  // Set position to fixed
  el.style.position = 'fixed';
}


The proper solution is not to poke styles onto nodes, but to instead tie your screen-specific style tweaks to css classes that only affect your screen rendition of things:

@media screen { .freeze { position: fixed; } } /* Display-only definition */

+

document.getElementById('foo').className = "freeze";

As a bonus, this also makes it easy to change tons of styles with just one line of js, which makes things faster and easier to maintain, too.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜