Window.print()打印整个网站中的部分内容,打印后,原网页保持不变

demo

html代码:

<table align="center" class="ml70">
        <tbody>
            <tr>
                <td colspan="8">
                    <div align="center">
                        <b><span >不打印的内容部分//////////////////////</span></b></div>
                    <div>
            </tr>
        </tbody>
    </table>
    <a href="#" onclick="javascript:history.back(1); event.returnValue=false">
        << 返回</a><br />
            <!--startprint-->
            <br />
            <table align="center" class="ml70">
                <tbody>
                    <tr>
                        <td colspan="8">
                            <div align="center">
                                <b><span >//////////////////////要打印的内容部分//////////////////////</span></b></div>
                            <div>
                    </tr>
                </tbody>
            </table>
            <!--endprint-->
            <input type="button" value="打印" onClick="printPage()" />

            <iframe id="printf" src="" width="0" height="0" frameborder="0"></iframe>

js代码:

 <script type="text/javascript">  
        function printPage() {  
            //获取当前页的html代码  
            var bodyhtml = window.document.body.innerHTML;  
            //设置打印开始区域、结束区域  
            var startFlag = "<!--startprint-->";  
            var endFlag = "<!--endprint-->";  
            // 要打印的部分  
            var printhtml = bodyhtml.substring(bodyhtml.indexOf(startFlag),   
                    bodyhtml.indexOf(endFlag));  
            // 生成并打印ifrme  
            var f = document.getElementById('printf'); 
            f.contentDocument.write(printhtml);
            f.contentDocument.close();
            f.contentWindow.print();
        }  
    </script>

效果截图

打印取消后,页面还是第一张图那样子的。

然后在f.contentDocument.write(printhtml);这句之前加一句f.contentDocument.write('<style type="text/css"> /这里写你的打印样式/ </style>');或者f.contentDocument.write('<link rel="stylesheet" type="text/css" href="xxx.css">');

猜你喜欢

转载自blog.csdn.net/qq493820798/article/details/90703001