JavaScript realizes direct printing by clicking the button

  • 2020-11-25 07:06:57
  • OfStack

Many websites have this function, when browsing to the bottom will have a print button, click the print button to complete the printing function, the function is very good, human, the code is very simple.


<a href="javascript:window.print()"> The home of the script </a> 

This means that you can print the current page simply by calling the window.print () function.

However, the above is not perfect, because some web pages do not need to print a lot of content, here is how to print the specified content in the page.

The code is as follows:


<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="https://www.ofstack.com/" />
<title> Specifies what to print </title>
<script language="javascript"> 
function printdiv(printpage) 
{ 
var newstr = printpage.innerHTML; 
var oldstr = document.body.innerHTML; 
document.body.innerHTML =newstr; 
window.print(); 
document.body.innerHTML=oldstr; 
return false; 
} 
window.onload=function()
{
var bt=document.getElementById("bt");
var div_print=document.getElementById("div_print");
bt.onclick=function()
{
printdiv(div_print);
}
}
</script> 
</head> 
<body> 
<div id="div_print"> 
<h1 style="Color:Red"> This is the content to be printed </h1> 
</div>
<div style="Color:Red"> You are welcome </div> 
<input name="print" type="button" id="bt" value=" Click on the print " /> 
</body> 
</html> 

Special note: The print preview requires that the code be copied to the native test, otherwise an error will occur.

The above code has achieved the effect of printing the specified content of the web page, the following simple introduction 1 under the implementation process.

1. Implementation Principle:

document. body. innerHTML =newstr in js code, dynamic original body content is replaced with the content to be printed, after printing, the original content is restored, the principle is so simple, you can see the code comments.

2. Code comments:

1.function printdiv(printpage){}, declare 1 function to control printing, parameter is 1 object, the contents of this object will be printed.
2.var newstr = printpage.innerHTML; , gets what you want to print.
3.var oldstr = document.body.innerHTML.
document.body.innerHTML =newstr, replacing the original body with the content to be printed.
5.window.print(), start printing.
6. document. body. innerHTML=oldstr, and then restore the original contents of body.

3. Related Reading:

1. The ES65en. print() function can be seen in section 1 of the print() method of the window object.
2.onclick events refer to the onclick Events section 1 of javascript.

The above content is relatively simple and has a separate code comment to help you learn js's button click and print function. I hope this article is helpful for you.


Related articles: