在JavaScript中调用window.print打印指定div
window.print可以打印网页,但有时候我们只希望打印特定控件或内容,怎么办呢?
首先我们可以把要打印的内容放在div中,然后用下面的代码进行打印。
1 <html> 2 <head> 3 <script language="javascript"> 4 function printdiv(printpage) 5 { 6 var headstr = "<html><head><title></title></head><body>"; 7 var footstr = "</body>"; 8 var newstr = document.all.item(printpage).innerHTML; 9 var oldstr = document.body.innerHTML; 10 document.body.innerHTML = headstr+newstr+footstr; 11 window.print(); 12 document.body.innerHTML = oldstr; 13 return false; 14 } 15 </script> 16 <title>div print</title> 17 </head> 18 <body> 19 //HTML Page 20 //Other content you wouldn't like to print 21 <input name="b_print" type="button" class="ipt" onClick="printdiv('div_print');" value=" Print "> 22 <div id="div_print"> 23 <h1 style="Color:Red">The Div content which you want to print</h1> 24 </div> 25 //Other content you wouldn't like to print 26 //Other content you wouldn't like to print 27 </body> 28 29 </html>
转自 http://blog.csdn.net/bintime/article/details/4296401
打印时会闪一下,因为把oldstr替换成newstr了,页面会变成新的页面