在打印网页时执行的JavaScript [英] execute javascript when printing page

查看:149
本文介绍了在打印网页时执行的JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

打印页面时,JavaScript的code似乎被执行。结果
我怎么能确定,如果当前正在打印的页面?我做了一些JS-调整大小,并有处理打印有一点点不同。

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.

推荐答案

您不能,除了IE浏览器。没有其他的浏览器有一个前打印的事件。你可以,但是,针对特定的样式表仅适用于打印时:

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.

另一种选择是提供一种具有打印当前页按钮,用户。该按钮可以处理你的JavaScript,调用 window.print(),然后恢复更改:

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
}

window.print()方法总是块(在每一个浏览器我测试过),所以它的安全,随即恢复了变化。但是,如果用户选择通过菜单或工具栏打印,您的运气了。

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.

我处理这种情况下,在一个复杂的web应用程序的方法之一是有隐藏一切,但一个特殊的DIV的打印样式表。如果用户单击打印,他们会得到一个警告消息。如果他们点击打印按钮,那么该分区将用正确的信息填充。这不是很大,但至少他们没有得到垃圾的几页。

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.

这篇关于在打印网页时执行的JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆