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

  

原文地址:https://www.cnblogs.com/babietongtianta/p/4961142.html