Home>Article>Web Front-end> How to implement printing operation in JavaScript
In JavaScript, you can use the print() method of the Window object to implement the printing operation, with the syntax format "window.print()". The print() method is used to print the contents of the current window; calling the print() method will generate a print preview pop-up box, allowing the user to set print requests.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Use window.print() directly;
First get the element html content (it is recommended to use inline styles if there are styles)
var newstr = document.getElementById(myp).innerHTML;//得到需要打印的元素HTML
Save the entire html of the current page, because the window.print() printing operation prints all the contents of the current page, so first Save the current page so you can restore it later.
var oldstr = document.body.innerHTML;//保存当前页面的HTML
Replace the current page with the print content HTML
document.body.innerHTML = newstr;
Perform the print operation
window.print();
Restore the current page
document.body.innerHTML = oldstr;
Method example:
//myp为需要打印的元素ID function printpage(myp){ var newstr = document.getElementById(myp).innerHTML; var oldstr = document.body.innerHTML; document.body.innerHTML = newstr; window.print(); document.body.innerHTML = oldstr; return false; }
[Recommended learning:javascript advanced tutorial]
The above is the detailed content of How to implement printing operation in JavaScript. For more information, please follow other related articles on the PHP Chinese website!