【问题标题】:Issue with window.print on SafariSafari 上的 window.print 问题
【发布时间】:2015-07-30 09:54:50
【问题描述】:

我有一个页面要打印一些内容。在打印的那一刻,一些 div 必须被隐藏,只有一个必须出现。该代码在 Chrome、Firefox 和 IE 上运行良好,但在 Safari 上无法运行。

这是我的 JS:

$(".printButton").on("click", function (event) {
    event.preventDefault();

    $("form").attr("style", "display: none !important");
    $("body").append("<div class='divToBePrinted' style='display: block !important;'></div>");
    $(".content").clone().appendTo('.divToBePrinted');

    window.print();

    $("form").removeAttr("style");
    $(".divToBePrinted").remove();
});

这是我的简化 HTML:

<html>
    <body>
        <form>
            <!-- Other content -->
            <div class="content">
                Content to be printed.
            </div>
            <button class="printButton"></button>
            <!-- Other content -->
        </form>
    </body>
</html>

在 Safari 上,window.print() 似乎在 event.preventDefault() 之前执行,捕获整个页面进行打印。

编辑:我尝试像下面那样使用 setTimeout,但它没有用。有一个专门用于打印的 CSS,但文件非常大。我试图删除它,但我得到了相同的结果:在所有浏览器中都可以正常工作,但在 Safari 上却不行。

带有 setTimeout 的 JS:

$(".printButton").on("click", function (event) {
event.preventDefault();

$("form").attr("style", "display: none !important");
$("body").append("<div class='divToBePrinted' style='display: block !important;'></div>");
$(".content").clone().appendTo('.divToBePrinted');

//setTimeout(window.print, 1000); -- I tried this way

// And this way
setTimeout(function () {
    window.print();

    $("form").removeAttr("style");
        $(".divToBePrinted").remove();
    }, 0);
});

编辑 2:我尝试将 1000 毫秒设置为 setTimeout 并且它在大多数情况下都有效,但这不是最终解决方案,我将进行新的研究以找到更好的方法。

setTimeout(function () {
    window.print();

    $("form").removeAttr("style");
    $(".divToBePrinted").remove();
}, 1000);

【问题讨论】:

    标签: javascript jquery printing safari


    【解决方案1】:

    onafterprint 事件似乎在 window.print 之后几乎立即触发。

    在大多数浏览器上,直到用户单击打印对话框上的打印才会调用此事件,但在 Safari 上,它似乎会在打印对话框出现时触发。

    【讨论】:

      【解决方案2】:

      好吧,在尝试了很多事情之后,我仍然不明白为什么 window.print() 事件会在 Safari 上的其他事件之前触发。但我使用@media print 解决了为该页面创建单独的 CSS 文件的问题。该文件负责隐藏/显示必须出现在打印件上的 div。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-29
        • 1970-01-01
        • 2020-05-28
        • 1970-01-01
        • 2014-10-06
        • 1970-01-01
        相关资源
        最近更新 更多