zoukankan      html  css  js  c++  java
  • JavaScript 打印Div内容

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Untitled Page</title>
    
        <script language="javascript" type="text/javascript">
            function printDiv(divID) {
                //Get the HTML of div
                var divElements = document.getElementById(divID).innerHTML;
                //Get the HTML of whole page
                var oldPage = document.body.innerHTML;
    
                //Reset the page's HTML with div's HTML only
                document.body.innerHTML = 
                  "<html><head><title></title></head><body>" + 
                  divElements + "</body>";
    
                //Print Page
                window.print();
    
                //Restore orignal HTML
                document.body.innerHTML = oldPage;
    
              
            }
        </script>
    
    </head>
    <body>
        <form id="form1" runat="server">
        <div id="printablediv" style=" 100%; background-color: Blue; height: 200px">
            请打印这里
        </div>
        <div id="donotprintdiv" style=" 100%; background-color: Gray; height: 200px">
            这里是不打印的
        </div>
        <input type="button" value="Print 1st Div" onclick="javascript:printDiv('printablediv')" />
        </form>
    </body>
    </html>
    

      

    如果打印的网页设置引用了CSS样式文件,需要对样式文件进行导入,修改后的方法如下:

    function printDiv(divID,title) {
            
        var links = document.getElementsByTagName("link");
    
        var styleContent = "";
    
        for (var i = 0, l = links.length; i < l; i++) {
            var src = links[i].href;
    
            styleContent += "<link href="" + src + "" rel="stylesheet" type="text/css" />";
        }
    
        //Get the HTML of div
        var divElements = document.getElementById(divID).innerHTML;
        //Get the HTML of whole page
        var oldPage = document.body.innerHTML;
        
        var titleDiv = "<div style="text-align:center;100%;"><h2>" + title + "</h2></div>";
    
        //Reset the page's HTML with div's HTML only
        document.body.innerHTML =
          "<html><head><title>报表打印</title>" + styleContent + "</head><body>" + titleDiv + 
          divElements + "</body>";
        
    
        window.print();
    
    
        //Restore orignal HTML
        document.body.innerHTML = oldPage;
    }
    

      

  • 相关阅读:
    ["Visual Studio快捷键" ,"Vs","IDEA快捷键"]
    文件夹
    x
    软考.第一章-信息化和信息系统
    软考.起航篇
    Global.asax.cs 为 /.aspx 执行子请求时出错。 Server.Transfer
    网关我选 Spring Cloud Gateway
    我面向 Google 编程,他面向薪资编程
    JDK 13 都已经发布了,Java 8 依然是最爱
    Spring Cloud 系列之 Spring Cloud Stream
  • 原文地址:https://www.cnblogs.com/babietongtianta/p/4961142.html
Copyright © 2011-2022 走看看