在JavaScript中调用window.print打印指定div

使用JavaScript打印特定网页内容
本文介绍如何使用JavaScript实现仅打印网页中的特定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.youkuaiyun.com/bintime/article/details/4296401

打印时会闪一下,因为把oldstr替换成newstr了,页面会变成新的页面

转载于:https://www.cnblogs.com/guide2it/p/3470607.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值