How to print only a selected HTML element?

前端 未结 8 2035
感动是毒
感动是毒 2020-11-29 05:11

I am trying to implement a print feature in HTML. I know I can print the whole page with window.print(), but how do I print only a specific page element? For ex

相关标签:
8条回答
  • 2020-11-29 05:29

    Created something generic to use on any HTML element

    HTMLElement.prototype.printMe = printMe;
    function printMe(query){
      var myframe = document.createElement('IFRAME');
      myframe.domain = document.domain;
      myframe.style.position = "absolute";
      myframe.style.top = "-10000px";
      document.body.appendChild(myframe);
      myframe.contentDocument.write(this.innerHTML) ;
      setTimeout(function(){
      myframe.focus();
      myframe.contentWindow.print();
      myframe.parentNode.removeChild(myframe) ;// remove frame
      },3000); // wait for images to load inside iframe
      window.focus();
     }
    

    Usage:

    document.getElementById('xyz').printMe();
    document.getElementsByClassName('xyz')[0].printMe();
    

    Hope this help
    Regards
    Gaurav Khurana

    0 讨论(0)
  • 2020-11-29 05:32

    If you are familiar to jQuery, you can use jQuery Print Element plugin like this:

    $('SelectorToPrint').printElement();
    
    0 讨论(0)
  • 2020-11-29 05:41

    If I understood you well you can use CSS3 to print your selected HTML element.

    @media print {
      body.print-element *:not(.print) {
        display: none;
      }
    }
    

    Notice, that you just need a selector. This allows you to easily print an element or the entire page using CSS classes.

    Here you can check a working example: https://jsfiddle.net/gengns/d50m8ztu/

    0 讨论(0)
  • 2020-11-29 05:42

    Here is another (perhaps a more modern?) solution:

    <link rel="stylesheet" media="print" href="print.css">
    
    0 讨论(0)
  • 2020-11-29 05:43

    You could use a print specific CSS stylesheet and hide everything but what you want printed.

    <div class="no-print">I won't print</div><div class="something-else">I will!</div>

    Just the no-print class will be hidden, but anything with a print class will show.

    <style type="text/css" media="print">
       .no-print { display: none; }
    </style>
    
    0 讨论(0)
  • 2020-11-29 05:44

    Printing an Html or a Selected Html is easy using Print.Js Add Print.Js Library

    http://printjs.crabbly.com/
    
      <form method="post" action="#" id="printJS-form">
        ...
      </form>
    
     <button type="button" onclick="printJS('printJS-form', 'html')">
        Print Form
     </button>
    
    0 讨论(0)
提交回复
热议问题