我想打开一个新窗口/选项卡,在文档中放入一些 HTML,然后调出浏览器打印对话框以打印该新窗口。我正在使用以下内容来完成此操作:
var w = window.open();
w.document.write(html);
w.document.close();
html
包含:
...<body onload="window.print()">...</body>...
一切正常,弹出窗口,并显示新页面的打印对话框,但是,由于某种原因,浏览器在显示打印对话框之前没有等待页面上的所有图像加载。它导致某些图像无法打印。
有很多图片,它们是在服务器端动态生成的(每张加载大约需要 1 秒)。如何强制浏览器仅在加载所有图像后打印?
这发生在我已经确认的 Chrome 和 Firefox 中。感谢您的帮助。
最佳答案
尝试将打印机调用置于最后一张图像的 onload 事件中。
<img onload="window.print()" ... />
编辑:
OP 的完整答案如下所示:
I came up with the following script using @chockleyc's answer as inspiration. I couldn't just use the last image because they don't necessarily load in order. The following script will print the page after all images have loaded (uses jQuery):
var hasPrinted = false;
$(document).ready(function(){
$('img').load(function(){
var imgs = $('img');
var loadedAll=true;
for(var i=0;i<imgs.length;i++){
loadedAll &= $(imgs[i])[0].complete;
}
if (loadedAll && !hasPrinted) {
console.log('printing');
hasPrinted = true;
window.print();
}
else {
console.log('not all images have loaded');
}
})
});
关于javascript - 在缺少图像的 JavaScript 中打印弹出窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17534415/