zoukankan      html  css  js  c++  java
  • 打印网页中某一段内容

    很久之前,Insus.NET的写过一篇,打印Web网页的。
    今次尝试使用jQuery来实现。

    打印的网页如下,需要打印的内容,使用一个div标签包含起来。并给此div一个ID值,稍后在jQuery代码会选择到此div。
    另外还有放置一个铵钮,让用户点一点此铵钮,就能调用打印对话框进行打印。

    <div id="divPrintContents">
            标题标题标题标题标题标题标题标题标题标题
            <br />
            <hr />
            <br />
            内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容 <br />
            内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容<br />
            内容内容内容内容内容内容内容<br />
            内容内容内容内容内容内容内容内容内容内容内容内容内容内容<br />
            内容内容内容内
        </div>
        <br />
        <input type="button" id="btnPrint" value="打印" />
    Source Code


    既然要使用jquery,那得在网页上引用jQuery类库:

    <script src="~/Scripts/jquery-3.1.1.js"></script>


    jQuery代码:

     $(function () {
                $("#btnPrint").click(function () {
                    var frame1 = $('<iframe />');
                    frame1[0].name = "frame1";
                    frame1.css({ "position": "absolute", "top": "-1000000px" });
    
                    $("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>');
                    frameDoc.document.write('<head>');
                    frameDoc.document.write('<title>分析报表</title>');
                    frameDoc.document.write('<link href="style.css" rel="stylesheet" type="text/css" />');
                    frameDoc.document.write('</head>');
    
                    frameDoc.document.write('<body>');
                    frameDoc.document.write($("#divPrintContents").html());
                    frameDoc.document.write('</body>');
    
                    frameDoc.document.write('</html>');
                    frameDoc.document.close();
    
                    setTimeout(function () {
                        window.frames["frame1"].focus();
                        window.frames["frame1"].print();
                        frame1.remove();
                    }, 500);
                });
            });
    Source Code

     
    演示:

  • 相关阅读:
    Vue中关于路由传参query和params的区别
    网页从输入网址到渲染完成经历了哪些过程?
    http常见的状态码
    项目中遇到哪些难点,如何解决的
    vue双向绑定、Proxy、defineproperty
    Proxy相比于defineProperty的优势
    axios
    虚拟DOM
    vue、react、angular三大框架对比 && 与jQuery的对比
    DOS、DOS攻击、DDOS攻击、DRDOS攻击
  • 原文地址:https://www.cnblogs.com/insus/p/7765456.html
Copyright © 2011-2022 走看看