In the previous article "Teach everyone to declare variables in different ways in JavaScript", I introduced you how to declare variables in different ways in JavaScript. Friends who are interested can learn about it. ~
The main content of this article is to teach you how to use JavaScript to print the content of div elements!
So to print the content of the div in JavaScript, we need to sort out the implementation ideas:
First store the content of the div in a JavaScript variable; then click the print button to extract the HTML div element; then create a JavaScript pop-up window and write the extracted content of the HTML div element into the pop-up window; and finally print the window using the JavaScript window print command.
Below we will implement it in two ways:
The first method: This example uses the JavaScript window print command to print the content of the div element
<!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title></title> <script> function printDiv() { var divContents = document.getElementById("GFG").innerHTML; var a = window.open('', '', 'height=500, width=500'); a.document.write('<html>'); a.document.write('<body > <h1>Div contents are <br>'); a.document.write(divContents); a.document.write('</body></html>'); a.document.close(); a.print(); } </script> </head> <body style="text-align:center;"> <div id="GFG" style="background-color:#00a2d4;"> <h2>PHP中文网</h2> <p> 这是在div中,点击按钮后则会显示打印。 </p> </div> <input type="button" value="点击打印" onclick="printDiv()"> </body> </html>
The effect before clicking the button is as follows:
Then we click the "Click to Print" button, and the following picture appears:
Second method: This example uses the JavaScript window print command to print the content of the div element
<!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title></title> <script> function printDiv() { var divContents = document.getElementById("GFG").innerHTML; var a = window.open('', '', 'height=500, width=500'); a.document.write('<html>'); a.document.write('<body > <h1>Div contents are <br>'); a.document.write(divContents); a.document.write('</body></html>'); a.document.close(); a.print(); } </script> </head> <body> <center> <div id="GFG" style="background-color:#9a9afb;"> <h2>PHP中文网</h2> <table border="1px"> <tr> <td>姓名</td> <td>分数</td> </tr> <tr> <td>张三</td> <td>110</td> </tr> </table> </div> <p> 表格在div中,点击按钮就会打印出来。 </p> <input type="button" value="点击打印" onclick="printDiv()"> </center> </body> </html>
The effect before clicking the button is as follows:
The effect after clicking the "Click to Print" button is as follows:
Finally, I would like to recommend "JavaScript Basic Tutorial》~Welcome everyone to learn~
The above is the detailed content of Detailed explanation of how to use JavaScript to print the content of div elements. For more information, please follow other related articles on the PHP Chinese website!