如何在打印事件上触发 javascript? [英] How to trigger javascript on print event?

查看:29
本文介绍了如何在打印事件上触发 javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在用户打印页面时触发 javascript 事件?当用户选择打印页面时,我想删除对 j​​avascript 库的依赖,因为该库非常适合屏幕但不适合打印.

Is it possible to trigger a javascript event when a user prints a page? I would like to remove a dependancy on a javascript library, when a user opts to print a page, as the library is great for screen but not for print.

知道如何实现这一目标吗?

Any idea how to achieve this?

推荐答案

对于任何在 Google 上偶然发现此答案的人,让我尝试澄清一下:

For anyone stumbling upon this answer from Google, let me try to clear things up:

正如 Ajay 指出的那样,有两个事件被触发用于打印,但它们没有得到很好的支持;据我所知,它们仅在 Internet Explorer 和 Firefox (6+) 浏览器中受支持.这些事件是 window.onbeforeprint 和 window.onafterprint,它们(如您所料)将在打印作业之前和之后触发.

As Ajay pointed out, there are two events which are fired for printing, but they are not well-supported; as far as I have read, they are only supported in Internet Explorer and Firefox (6+) browsers. Those events are window.onbeforeprint and window.onafterprint, which (as you'd expect) will fire before and after the print job.

但是,正如 Joe 的链接中所指出的那样 (https://stackoverflow.com/a/9920784/578667),这并不是它在所有情况下的实现方式.在大多数情况下,两个事件都在对话之前触发;在其他情况下,脚本执行可能会在打印对话框期间暂停,因此这两个事件可能会同时触发(在对话框完成后).

However, as pointed out in Joe's link (https://stackoverflow.com/a/9920784/578667), that's not exactly how it is implemented in all cases. In most cases, both events fire before the dialog; in others, script execution might be halted during the print dialog, so both events may fire at the same time (after the dialog has been completed).

有关这两个事件的更多信息(和浏览器支持):

For more information (and browser support) for these two events:

https://developer.mozilla.org/en-US/docs/DOM/window.onbeforeprint

https://developer.mozilla.org/en-US/docs/DOM/window.onafterprint

简短的回答:如果您希望干扰打印流程,请不要.如果您希望在打印后触发代码,它不会按您想要的方式工作;预计浏览器支持不佳,并尝试优雅地降级.

The short answer: if you're hoping to interfere with the print flow, don't. If you're hoping to trigger code after printing, it's not going to work how you're wanting; expect poor browser support, and try to degrade gracefully.

这篇关于如何在打印事件上触发 javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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