JS局部打印两种方法

所有浏览器都可以

<html>
<head title="">
    <title>测试打印</title>
    <style media="print">
        /*只应用于打印的样式*/
        .noprint {
            display: none;
        }
    </style>
    <script>
//通过标签控制
function printDiv1(oper) { bdhtml = window.document.body.innerHTML;//获取当前页的html代码 sprnstr = "<!--startprint" + oper + "-->";//设置打印开始区域 eprnstr = "<!--endprint" + oper + "-->";//设置打印结束区域 prnhtml = bdhtml.substring(bdhtml.indexOf(sprnstr) + 18); //从开始代码向后取html prnhtml = prnhtml.substring(0, prnhtml.indexOf(eprnstr));//从结束代码向前取html window.document.body.innerHTML = prnhtml; window.print();
window.document.body.innerHTML = bdhtml; } //通过样式控制
function printDiv2() { window.print(); } </script> </head> <body> <!--startprint1--> <div>需要打印的(如需打印背景: 在Internet选项--高级--在“打印”一项选上“打印背景颜色和图象”)</div> <!--endprint1--> <div class="noprint"> <div>不需要打印的</div> <input type="button" value="打印(innerHTML法)" onclick="printDiv1(1);" /> <input type="button" value="打印(样式法)" onclick="printDiv2();" /> </div> </body> </html>

如何打印背景:

IE: 在Internet选项--高级--在“打印”一项选上“打印背景颜色和图象”

或者新版的IE:

Firefox:

Chrome:

原文地址:https://www.cnblogs.com/xachary/p/3986027.html