How to print only a selected HTML element?

前端 未结 8 2036
感动是毒
感动是毒 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:46

    If you are using JQuery, you can use clone to do the following:

    function printElement(e) {
      var ifr = document.createElement('iframe');
      ifr.style='height: 0px; width: 0px; position: absolute'
      document.body.appendChild(ifr);
    
      $(e).clone().appendTo(ifr.contentDocument.body);
      ifr.contentWindow.print();
    
      ifr.parentElement.removeChild(ifr);
    }
    

    and use like so: printElement(document.getElementById('myElementToPrint'))

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

    Simple html and pure javascript works best. Parameter "this" refers to current id, so that function is universal for all ids with textual content.

    html body:

    <div id="monitor" onclick="idElementPrint(this)">text i want to print</div>
    

    pure javascript:

    //or: monitor.textContent = "click me to print textual content";
    
    const idElementPrint = (idin) => {
        let ifram = document.createElement("iframe");
        ifram.style = "display:none";
        document.body.appendChild(ifram);
        pri = ifram.contentWindow;
        pri.document.open();
        pri.document.write(idin.textContent);
        pri.document.close();
        pri.focus();
        pri.print();
        }
    
    0 讨论(0)
提交回复
热议问题