4

我想用javascript函数打印网页window.print()

该页面包含带有滚动条的 div

但打印仅显示部分 div

我试图添加到 css

@media print
{
 .myDiv
  { 
    height:100%;
  }

}

但它不起作用,

我想在没有滚动条的情况下显示所有 div 内容我该怎么做?

4

3 回答 3

5

此方法可让您打印任意 div。

使用 jQuery:

function print(selector) {
    var $print = $(selector)
        .clone()
        .addClass('print')
        .prependTo('body');

    //window.print() stops JS execution
    window.print();

    //Remove div once printed
    $print.remove();
}

还有一些 CSS:

body, html {
    width: 100%;
    height: 100%;
}

.print {
     position: fixed;
     overflow: auto;
     width: 100%;
     height: 100%;
     z-index: 100000; /* CSS doesn't support infinity */

     /* Any other Print Properties */
}
于 2013-08-15T08:49:13.967 回答
4

尝试这个

注意:不要给 div 内联样式

  <head>
    <style type="text/css">
    .result{ height:200px;overflow:auto;}
    </style>
    <style type="text/css" media="print">
    @media print{ .result{ height:100%;overflow:visible;} } 
    </style>
    <title></title>
  </head>
  <body>
    <div class="result">
      content goes here..
    </div>
    <form>
      <input type="button" value="print" onclick="window.print();" />
    </form>
  </body>
于 2014-10-30T09:19:11.037 回答
2

这是使用 javascript 打印 div 内容的代码。

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


<div id="printme" style="width: 100%; background-color: Blue; height: 200px">
    Print me I am in 1st Div
</div>   
<input type="button" value="Print" onclick="javascript:printDiv('printme')" />
于 2013-08-15T08:37:04.297 回答