Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

browser - execute javascript when printing page

when printing a page, the javascript code seems to be executed.
how can I determine, if the page is currently being printed? I do some js-resizing, and have to handle printing a little bit different.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can't, except for IE browsers. No other browser has a before print event. You can, however, target a specific stylesheet to only apply while printing:

<!-- In head -->
<link rel="stylesheet" type="text/css" media="print" href="print.css" />

This stylesheet will be applied before printing. This allows you to perform some amazing changes, including hiding major sections, moving items around, and performing print-only styling, such as page breaks.

Another option is to provide the user with a "Print this Page" button. That button can handle your JavaScript, call window.print(), and revert the changes:

function printMe() {
    // perform changes
    window.print();
    // revert changes
}

The window.print() method always blocks (in every browser I've tested), so it's safe to immediately revert the changes afterward. However, if the user choose to print via the menu or toolbar, you are out of luck.

One way I handled that case in a complex web-app was to have a print stylesheet that hid everything but a special DIV. If the user clicked print, they would get a warning message. If they clicked the print button, then that div would be populated with the correct information. It's not great, but at least they didn't get several pages of garbage.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...