js打印隐藏的div,可自定义样式

 

 

 

这里是全部代码,可以直接运行。js需要自行导入

 

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        <script src="js/jquery-1.4.4.min.js" type="text/javascript" charset="utf-8"></script>
        <!--<script src="js/jquery.jqprint-0.3.js" type="text/javascript" charset="utf-8"></script>
        <link rel="stylesheet" type="text/css" href="css/print.css"/>-->
    </head>
    <body>
        <div id="printcontent" style="display: none;">
        
        <div id="print-div">
            <style type="text/css">
                .title{
                    color: red;
                }
            </style>
            <!--需要打印的都在这个div-->
            <div class="title-div">
                <span class="title">电子验印结果记录单</span>
            </div>
            <table border="0" cellspacing="" cellpadding="">
                <!--<tr><th>Header</th></tr>-->
                <tr>
                    <td>验印时间:2021-03-19 16:39:35</td>
                    <td>账号:91310120MA1HQGCT3T</td>
                </tr>
                <tr>
                    <td colspan="2">户名:上海尊煜建筑劳务有限公司</td>
                </tr>
                <tr>
                    <td>凭证金额:2.00</td>
                    <td>出票日期:2021-03-19</td>
                </tr>
            </table>
        </div>
        
        
        </div>
        <button id="printBtn">打印</button>
    </body>
    <script type="text/javascript">
        $("#printBtn").click(function() {
            doPrint3();
        })
        
        function doPrint3(){
    
    //判断iframe是否存在,不存在则创建iframe
    var iframe=document.getElementById("print-iframe");
    if(!iframe){  
            var el = document.getElementById("printcontent");
            iframe = document.createElement('IFRAME');
            var doc = null;
            iframe.setAttribute("id", "print-iframe");
            iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;');
            document.body.appendChild(iframe);
            doc = iframe.contentWindow.document;
            //这里可以自定义样式
//          <link rel="stylesheet" type="text/css" href="css/print.css"/>
            doc.write('<link rel="stylesheet" type="text/css" href="css/print.css"/>');
            doc.write('<div>' + el.innerHTML + '</div>');
            doc.close();
            iframe.contentWindow.focus();            
    }
    iframe.contentWindow.print();
    document.body.removeChild(iframe);
//  if (navigator.userAgent.indexOf("MSIE") > 0){
//      document.body.removeChild(iframe);
//  }
    
}
    </script>
</html>
View Code

 

posted @ 2021-04-08 22:10  沉迷编程的程序员  阅读(87)  评论(0编辑  收藏  举报