使用JS的 window.print() 打印指定页面区域

JS自带的 window.print() 方法可以打印当前 “整个” 页面的内容,但如果需要打印特定的内容时,只能通过其他“邪门歪道”进行转换。例:

HTML代码:

<div class="row form-horizontal">
<!--startprint-->
<div id="code-list">
<!-- 二维码/条形码 展示处 -->
</div>
  <!-- 注:当打印的区域包括自定义样式时,必须把对应的样式带进来,否则打印预览视图展示的内容样式会出问题的! -->
<style>
.code-item{
width:80px;
height:80px;
margin: 10px 0 30px 0;
}

.barcode-item{
text-align: center;
}

#code-list{
text-align: -webkit-center;
}

.codeimg{
height: 80px;
}
</style>
<!--endprint-->
<div style="text-align: center;" id="show-button-print">
<button type="button" onclick="printDivArea();" class="btn btn-primary">打印</button>
</div>
</div>

JS代码实现
function printDivArea(){    //打印指定区域的方法
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();
setTimeout(location.reload(), 2000);    //重新加载页面
}
posted @ 2019-05-30 18:02  暗影寒街  阅读(654)  评论(0)    收藏  举报