JavaScript prints an example of a specified area of a web page

  • 2020-03-30 02:49:22
  • OfStack

JavaScript print page to specify div area principle: use window.open() to open a new page (window) in the browser, use window.document.write() to write the content of the specified div area to the new window document, document.close() to close the document, use window.print() to call the printer to print the current document.

JavaScript print function myPrint(obj) :


function myPrint(obj){
    //Open a newWindow, newWindow
    var newWindow=window.open(" Print window ","_blank");
    //The contents of the div to be printed
    var docStr = obj.innerHTML;
    //The print is written to the newWindow document
    newWindow.document.write(docStr);
    //Close the document
    newWindow.document.close();
    //Invoke printer
    newWindow.print();
    //Close the newWindow page
    newWindow.close();
}

Myprint () call method:

myPrint(document.getElementById('printDivID'));

Example code:

<script>
function myPrint(obj){
    var newWindow=window.open(" Print window ","_blank");
    var docStr = obj.innerHTML;
    newWindow.document.write(docStr);
    newWindow.document.close();
    newWindow.print();
    newWindow.close();
}
</script>
<div id="print">
<hr />
    Print demonstration area , Clicking print will load the contents here in the new window! 
<hr />
</div>
<button onclick="myPrint(document.getElementById('print'))"> play   print </button>


Related articles: