【发布时间】: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