Home  >  Article  >  Web Front-end  >  How to implement printing operation in JavaScript

How to implement printing operation in JavaScript

青灯夜游
青灯夜游Original
2021-05-18 15:04:056402browse

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

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!

Statement:
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