Print
only?

前端 未结 30 1600
暖寄归人
暖寄归人 2020-11-22 00:25

How do I print the indicated div (without manually disabling all other content on the page)?

I want to avoid a new preview dialog, so creating a new window with this

相关标签:
30条回答
  • 2020-11-22 00:52

    I have a better solution with minimal code.

    Place your printable part inside a div with an id like this:

    <div id="printableArea">
          <h1>Print me</h1>
    </div>
    
    <input type="button" onclick="printDiv('printableArea')" value="print a div!" />
    

    Then add an event like an onclick (as shown above), and pass the id of the div like I did above.

    Now let's create a really simple javascript:

    function printDiv(divName) {
         var printContents = document.getElementById(divName).innerHTML;
         var originalContents = document.body.innerHTML;
    
         document.body.innerHTML = printContents;
    
         window.print();
    
         document.body.innerHTML = originalContents;
    }
    

    Notice how simple this is? No popups, no new windows, no crazy styling, no JS libraries like jquery. The problem with really complicated solutions (the answer isn't complicated and not what I'm referring to) is the fact that it will NEVER translate across all browsers, ever! If you want to make the styles different, do as shown in the checked answer by adding the media attribute to a stylesheet link (media="print").

    No fluff, lightweight, it just works.

    0 讨论(0)
  • 2020-11-22 00:52

    Sandro's method works great.

    I tweaked it to allow for allowing multiple printMe links, particularily to be used in tabbed pages and expanding text.

    function processPrint(printMe){ <-- calling for a variable here

    var printReadyElem = document.getElementById(printMe); <-- removed the quotes around printMe to ask for a variable

    <a href="javascript:void(processPrint('divID'));">Print</a> <-- passing the div ID to be printed on to the function to turn the printMe variable into the div ID. single quotes are needed

    0 讨论(0)
  • 2020-11-22 00:54

    I tried many of the solutions provided.None of them worked perfectly. They either lose CSS or JavaScript bindings. I found a perfect and easy solution that neither losses CSS nor JavaScript bindings.

    HTML:

    <div id='printarea'>
        <p>This is a sample text for printing purpose.</p>
        <input type='button' id='btn' value='Print' onclick='printFunc();'>
    </div>
    <p>Do not print.</p>
    

    Javascript:

    function printFunc() {
        var divToPrint = document.getElementById('printarea');
        var htmlToPrint = '' +
            '<style type="text/css">' +
            'table th, table td {' +
            'border:1px solid #000;' +
            'padding;0.5em;' +
            '}' +
            '</style>';
        htmlToPrint += divToPrint.outerHTML;
        newWin = window.open("");
        newWin.document.write("<h3 align='center'>Print Page</h3>");
        newWin.document.write(htmlToPrint);
        newWin.print();
        newWin.close();
        }
    
    0 讨论(0)
  • 2020-11-22 00:55

    I had multiple images each with a button and needed to click on a button to print each div with an image. This solution works if I have disabled cache in my browser, and the image size doesn't change in Chrome:

            function printDiv(divName) {
    
            var printContents = document.getElementById(divName).innerHTML;
            w = window.open();
    
            w.document.write(printContents);
            w.document.write('<scr' + 'ipt type="text/javascript">' + 'window.onload = function() { window.print(); window.close(); };' + '</sc' + 'ript>');
    
            w.document.close(); // necessary for IE >= 10
            w.focus(); // necessary for IE >= 10
    
            return true;
        }
    
    <div id="printableArea">
          <h1>Print me</h1>
    </div>
    
    <input type="button" onclick="printDiv('printableArea')" value="print a div!" />
    
    0 讨论(0)
  • 2020-11-22 00:56

    I didn't really like any of these answers as a whole. If you have a class (say printableArea) and have that as an immediate child of body, then you can do something like this in your print CSS:

    body > *:not(.printableArea) {
        display: none;
    }
    
    //Not needed if already showing
    body > .printableArea {
        display: block;
    }
    

    For those looking for printableArea in another place, you would need to make sure the parents of printableArea are shown:

    body > *:not(.parentDiv),
    .parentDiv > *:not(.printableArea) {
        display: none;
    }
    
    //Not needed if already showing
    body > .printableArea {
        display: block;
    }
    

    Using the visibility can cause a lot of spacing issues and blank pages. This is because the visibility maintains the elements space, just makes it hidden, where as display removes it and allows other elements to take up its space.

    The reason why this solution works is that you are not grabbing all elements, just the immediate children of body and hiding them. The other solutions below with display css, hide all the elements, which effects everything inside of printableArea content.

    I wouldn't suggest javascript as you would need to have a print button that the user clicks and the standard browser print buttons wouldn't have the same effect. If you really need to do that, what I would do is store the html of body, remove all unwanted elements, print, then add the html back. As mentioned though, I would avoid this if you can and use a CSS option like above.

    NOTE: You can add whatever CSS into the print CSS using inline styles:

    <style type="text/css">
    @media print {
       //styles here
    }
    </style>
    

    Or like I usually use is a link tag:

    <link rel="stylesheet" type="text/css" media="print" href="print.css" />
    
    0 讨论(0)
  • 2020-11-22 00:56
    1. Give whatever element you want to print the id printMe.

    2. Include this script in your head tag:

      <script language="javascript">
          var gAutoPrint = true;
      
          function processPrint(){
      
          if (document.getElementById != null){
          var html = '<HTML>\n<HEAD>\n';
          if (document.getElementsByTagName != null){
          var headTags = document.getElementsByTagName("head");
          if (headTags.length > 0) html += headTags[0].innerHTML;
          }
      
          html += '\n</HE' + 'AD>\n<BODY>\n';
          var printReadyElem = document.getElementById("printMe");
      
          if (printReadyElem != null) html += printReadyElem.innerHTML;
          else{
          alert("Error, no contents.");
          return;
          }
      
          html += '\n</BO' + 'DY>\n</HT' + 'ML>';
          var printWin = window.open("","processPrint");
          printWin.document.open();
          printWin.document.write(html);
          printWin.document.close();
      
          if (gAutoPrint) printWin.print();
          } else alert("Browser not supported.");
      
          }
      </script>
      
    3. Call the function

      <a href="javascript:void(processPrint());">Print</a>
      
    0 讨论(0)
提交回复
热议问题