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;
    }
    

      

  • 相关阅读:
    C语言经典例题
    准确判断网络连接方式和当前连接状态
    [WMI实例]在网络连接断开时通知用户
    SciTE设置
    WQL语言初步
    以管理员身份运行bat
    AHK Primary
    AHK Run as Administrator In AHK
    为.VBS和.JS文件添加右键以管理员运行菜单
    PowerShell 随笔
  • 原文地址:https://www.cnblogs.com/babietongtianta/p/4961142.html
Copyright © 2011-2022 走看看