点关注不迷路

Max

网页中Div的打印

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>DIV打印Demo</title>
        <!--jqueryCDN-->
        <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    </head>
    <body>
        <div id="printdiv">
            <div style="text-align: center;">
                <h3>沁园春·雪</h3>
                <p>北国风光,千里冰封,万里雪飘。</p>
                <p>望长城内外,惟余莽莽;大河上下,顿失滔滔。</p>
                <p>山舞银蛇,原驰蜡象,欲与天公试比高。</p>
                <p>须晴日,看红装素裹,分外妖娆。</p>
                <p>江山如此多娇,引无数英雄竞折腰。</p>
                <p>惜秦皇汉武,略输文采;唐宗宋祖,稍逊风骚。</p>
                <p>一代天骄,成吉思汗,只识弯弓射大雕。</p>
                <p>俱往矣,数风流人物,还看今朝。</p>
            </div>
        </div>
        <button id="print">打印</button>
        <div style="text-align: center;">
            <p>这是一段废话不打印,hahahahahaahahahahahahahahahahahahaha</p> 
        </div>
    </body>
    <script>
        $("#print").click(function(){
            var frame1=$('<iframe />');
            frame1[0].name="frame1";
            //隐藏构造的iframe
            frame1.css({ "display": "none" });
            $("body").append(frame1);
            var frameDoc = frame1[0].contentWindow ? frame1[0].contentWindow :
                    frame1[0].contentDocument.document ? frame1[0].contentDocument.document : frame1[0].contentDocument;
            frameDoc.document.open();
            frameDoc.document.write('<html><head>');
            frameDoc.document.write('<title>沁园春·雪</title>');
            frameDoc.document.write('</head><body>');
            frameDoc.document.write($("#printdiv").html());
            frameDoc.document.write('</body></html>');
            frameDoc.document.close();
            
            window.frames["frame1"].focus();
            window.frames["frame1"].print();
            frame1.remove();
        })
    </script>
</html>

 

posted @ 2017-11-01 15:36  Max麦克斯  阅读(586)  评论(0编辑  收藏  举报