开发者

Revert to the page's original CSS with jQuery

开发者 https://www.devze.com 2022-12-13 10:42 出处:网络
I have a page with a \'printer friendly\' button that uses jQuery\'s .css() method to remove some backgrounds and border from specific elements, and change the font size. I can set another .css() meth

I have a page with a 'printer friendly' button that uses jQuery's .css() method to remove some backgrounds and border from specific elements, and change the font size. I can set another .css() method to change everything ba开发者_StackOverflowck to the way it was, but is there any easy way to revert everything on the page to its original CSS (aside from refreshing the page)?


You should define your print friendly styles as selector rules in your main css file

body.printfriendly .selector .rule
{
  font-size:bigger;
}

And then you can add and remove the printfriendly class on the body tag to show or hide the rules.

You can also use the @media print section to declare rules that only get applied when the user prints.

@media print 
{
   .selector .rule
   {
     font-size:bigger;
   }
}


You can remove all inline styles by doing something like

$('*[style]').removeAttr('style');

It will remove all styles set by jQuery, but also potentially any other inline styles set in the HTML. Not that I recommend it though.

I understand that you might not want to use a print style sheet. Some users would like to print the page as they see it, and you might want to add a preview before actually printing.

I recommend using a .printfriendly class that you can toggle to the body tag. That way you have full control in the CSS, and presentation layer.


You can use .removeClass to remove the class you attached

.addClass('printFriendly');

.removeClass('printFriendly');


Why you don't use a print style sheet that builds on top of you screen stylesheet? This would be much cleaner:

in your HTML template:

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

in your print.css:

@import "screen.css";
// overwrite disired parts of your screen.css

Now you can add a button with the following javascript command:

document.print(); 

to open the browsers default print promt.


The printer friendly button is pretty old school. CSS 2 has a media rule mechanism.

@media print {
  /* style sheet for print goes here */
}
0

精彩评论

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