gpt4 book ai didi

javascript - Safari 上的 window.print 问题

转载 作者:搜寻专家 更新时间:2023-11-01 04:41:02 25 4
gpt4 key购买 nike

我有一个页面有一些要打印的内容。在打印的那一刻,一些 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);

最佳答案

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

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

关于javascript - Safari 上的 window.print 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30310918/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com