How to implement printing operation in JavaScript

青灯夜游
Release: 2023-01-06 11:13:55
Original
6264 people have browsed it

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.

How to implement printing operation in JavaScript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Print the content in the specified element on the current page

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
Copy after login

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
Copy after login

Replace the current page with the print content HTML

document.body.innerHTML = newstr;
Copy after login

Perform the print operation

window.print();
Copy after login

Restore the current page

document.body.innerHTML = oldstr;
Copy after login

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; }
Copy after login

[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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!