是否有一种方法来监听正在使用javascript发送到打印机的页面

Is there a way to listen for a page being sent to the printer using javascript?

本文关键字:javascript 打印机 一种 监听 方法 是否      更新时间:2023-09-26

我试图创建一个javascript函数,其中内容在window.print启动之前被切换出来,然后在页面发送到打印机后将内容切换回来。我尝试过使用document.body.onfocus,但是一些打印方法(例如打印到PDF)在页面实际打印之前将焦点返回到body,从而将预期的内容替换为原始内容。

这是我目前拥有的,以及我认为我需要的监听器的位置:

function printNewContent() {
            var title = document.getElementById("OriginalTitle");
            var secondtext = document.getElementById("TextBlock2");
            var copy = document.getElementById("StandardCopy");
            var origtitle = title.innerHTML;
            var origcopy = copy.innerHTML;
            var newcopy = document.getElementById("NewCopy").innerHTML;
            title.innerHTML = "New Title";
            copy.innerHTML = newcopy;
            secondtext.className = "displayNone";
            window.print();
            //Listen for page to be sent to the printer
            title.innerHTML = origtitle;
            copy.innerHTML = origcopy;
            secondtext.className = "PrintOnly SecondTxt";
        }

我会将延迟与onfocus方法结合使用,但这不是一个万无一失的方法,我正在寻找尽可能稳定和一致的东西。任何建议都将非常感谢。谢谢!

另一种方法是使用CSS媒体查询来显示/隐藏网站上正在打印的内容。这比在打印之前尝试操作DOM并试图将其更改回来要好得多。

例如,假设你想让你的网页在屏幕上显示一个元素,但当它被打印出来时,你想隐藏它,并显示其他东西。您需要提前呈现屏幕版本和打印版本的HTML。

标记:

<div class="screen">
    This is the stuff normal users will see.
</div>
<div class="print">
    This is the stuff that will be printed.
</div>
CSS:

.print { display: none; }
@media print
{
    .print { display: block; }
    .screen { display: none; }
}

IE早就有onafterprint了。
在HTML5中,onafterprint也成为非ie浏览器的一个事件。关于onafterprint的详细信息,请参见MDC和W3C规范

我认为有onafterprint事件,但这只适用于internet explorer。

http://forums.asp.net/p/969033/1217303.aspx

你应该为不同的屏幕使用不同的样式css:

打印