JS实现页面部分内容打印
原理:在页面内嵌入一个隐藏的iframe,把要打印的内容赋值给iframe,再利用iframe的print()方法,实现打印。
主页面代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JS实现页面部分内容打印</title> <style> button { display: block; padding: 2px 20px 4px 20px; } .ifr1 { width:530px; height:120px; display:none; } .div1, .div2 { width:300px; line-height:100px; border:1px solid #000; margin-bottom:20px; text-align:center; } </style> <script type="text/javascript"> function myPrint() { var iwindow = window.frames['ifr1']; var idoc = iwindow.document; idoc.getElementById("myDiv").innerHTML = document.getElementById("div2").innerHTML; iwindow.print(); } </script> </head> <body> <div id="div1"><div class="div1">This is div1</div></div> <div id="div2"><div class="div2">This is div2</div></div> <button onclick="myPrint()">打印Div2</button> <iframe name="ifr1" src="iframe.html" class="ifr1"></iframe> </body> </html> |
iframe.html页面代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>iframe页面</title> <style> body { padding:0; margin:0 auto; } #myDiv { text-align:center; } .div2 { margin: 0 auto; width:500px; line-height:50px; font-size:24px; font-weight:bold; text-align:center; margin-top:10px; border:1px solid #ff0000; } </style> </head> <body> <div id="myDiv">This is iframe</div> </body> </html> |
说明:在iframe.html页面,对样式div2重新进行了设定。