用js在html页面实现打印功能示例

1.在head标签内加入一段js

<script language="javascript" type="text/javascript">
        function doPrint() { 
            bdhtml=window.document.body.innerHTML; //获取当前页的html代码
            sprnstr="<!--startprint-->"; //设置打印开始区域
            eprnstr="<!--endprint-->";//设置打印结束区域
            prnhtml=bdhtml.substr(bdhtml.indexOf(sprnstr)+17);//从开始代码向后取html
            prnhtml=prnhtml.substring(0,prnhtml.indexOf(eprnstr));//从结束代码向前取html
            window.document.body.innerHTML=prnhtml;
            window.print();
        }
    </script>

2.需要打印的内容用<!--startprint--><!--endprint-->包起来

<div>
        <!--startprint-->
        <!--打印内容开始-->
        开始和结束标签内就是需要打印的内容<br>
        <img src="https://www.baidu.com/img/baidu_jgylogo3.gif" /><br>
        <img src="https://www.baidu.com/img/baidu_jgylogo3.gif" /><br>
        <img src="https://www.baidu.com/img/baidu_jgylogo3.gif" /><br>
        <img src="https://www.baidu.com/img/baidu_jgylogo3.gif" />
        <!--打印内容结束-->
        <!--endprint-->
    </div>

3.加入一个打印按钮,调用之前的doPrint()方法

<input type="button"  />

通过以上3步连接打印机就可以打印了,需要注意一点,背景图是不能被打印出来的