How to print only a selected HTML element?

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

提交回复
热议问题