我们在网页开发过程中经常会有打印页面的需求,通过JS来实现的方法有很多,这里我做了一个整理,供大家参考。
通过:
window.print()
整体打印
<a href="javascrīpt:window.print()" rel="external nofollow" target="_self">打印</a>
现在就轻松实现了页面的打印,但是这种方式会将整个页面打印,如果想要实现指定区域的打印需要通过下面的设置
局部打印
首先,在html中,通过star和end来标记打印区域
<h1>这块内容不需要打印</h1>
<!--startprint-->
<div class="content">
这里是需要打印的内容
.....
</div>
<!--endprint-->
<h1>这块内容不需要打印</h1>
然后,在点击事件中添加如下代码
function doPrint() {
bdhtml=window.document.body.innerHTML;
sprnstr="<!--startprint-->";
eprnstr="<!--endprint-->";
prnhtml=bdhtml.substr(bdhtml.indexOf(sprnstr)+17);
prnhtml=prnhtml.substring(0,prnhtml.indexOf(eprnstr));
window.document.body.innerHTML=prnhtml;
window.print();
}
过滤打印区域的内容
例如
<!--startprint-->
<div class="content">
<button class="noprint">预览</button>
<button class="noprint">打印</button>
这里是需要打印的内容
.....
</div>
<!--endprint-->
上面的预览和打印按钮不希望打印,如果要过滤的话可以做下面的样式设置
<style type="text/css">
@media print {
.noprint{
display: none;
}
}
</style>
或者
<style type="text/css" media="print">
.noprint{
display: none;
}
</style>
两种写法任选其一
分页打印
使用 window.print() 打印时,如果内容超出会自动分页。但是我们如果需要自定义分页范围,如碰到表格分页打印,可以通过进行如下设置:
<table width="100%" border="0" cellpadding="0" cellspacing="0" style="page-break-after:always" >
</table>