JavaScript+CSS control printing format sample introduction

  • 2020-03-30 01:14:59
  • OfStack

1. Use the CSS of media="print" to control the style that refers to media as print in the testprint.html of the file to be printed
 
<link href="/style/print.css" rel="stylesheet" type="text/css" media="print"> 

/ style/print. CSS file
 
.noprint{display:none;} 

The style in print.css is used in testprint.html, which cannot be seen when browsing the web, but will work when printing, such as the following paragraph, after adding noprint, it is still realistic in the browser, but it is not displayed when printing:
 
<div class="noprint"> 
<input type="button" onclick="window.print();" value=" Print this page " /> 
</div> 

Of course print. The inside of the CSS styles you can literally write, change color (color images in black and white printer under the result is bad, can use another style print), font or something can be, literally play -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -

2. Use JavaScript to control

Because of this and that reason, some people may not be familiar with CSS, some people JavaScript is more awesome, sometimes JavaScript is a good choice
 
<script type="text/javascript"> 
<!-- 
//Automatically executes before printing
window.onbeforeprint = function(){ 
$("#test").hide(); 
} 

//Automatically executes after printing
window.onafterprint = function(){ 
$("#test").show(); 
} 
//--> 
</script> 


<div id="test"> This text will not be printed </div> 

Before printing, the window.onbeforeprint function is called, so you can do whatever you want, use your ingenuity to reconstruct one side of the HTML, and then print. Of course, after printing, we usually have to get it back, which is the window.onafterprint function

---------------------------------------------------------------

Tip: note that print as we all know is the window. The print (), actually also can print framework, such as window. Top. CenterFrame. MainFrame. Print ();

Related articles: