window.print() print all div content without scrol

2019-07-24 19:13发布

i want to print web page with javascript function window.print()

the page include div with scroll bar

But printing is displayed only part of the div

I tried to add to css

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

}

but it not work,

i want to show all div content without scroll bar how i do it?

3条回答
啃猪蹄的小仙女
2楼-- · 2019-07-24 19:46

This is code to print div content using javascript.

 <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')" />
查看更多
虎瘦雄心在
3楼-- · 2019-07-24 19:56

This method will let you print any arbitrary div.

Using 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();
}

And some 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 */
}
查看更多
等我变得足够好
4楼-- · 2019-07-24 20:13

try this

Note:dont give inline style to 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>
查看更多
登录 后发表回答