在JavaScript中打印弹出窗口缺失图像 [英] Print popup in JavaScript missing images

查看:112
本文介绍了在JavaScript中打印弹出窗口缺失图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打开一个新的窗口/选项卡,在文档中放入一些HTML,然后打开浏览器打印对话框以打印新窗口。我使用以下来完成这个:

  var w = window.open(); 
w.document.write(html);
w.document.close();

其中 html 包含:

  ...< body onload =window.print()> ...< / body> ... 

这一切都有效,窗口弹出,新页面显示打印对话框,但是,对于出于某种原因,浏览器在显示打印对话框之前并未等待页面上的所有图像加载。它会导致一些图像不能打印。



有很多图像,它们是在服务器端动态生成的(每次加载需要大约1秒)。我如何强制浏览器在所有图像加载后才打印?

这发生在我已确认的Chrome和Firefox中。

解决方案

尝试将您的打印机调用放入最后一张图片的onload事件中。
$ b

 < img onload =window.print()... /> 

编辑:

OP如下图所示:


我用@ chockleyc的答案提出了以下脚本作为灵感。我不能只使用最后一张图片,因为它们不一定按顺序装入。以下脚本将在所有图片加载后使用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('并非所有图像都已加载');
}
})
});


I want to open a new window/tab, put some HTML in the document, then bring up the browser print dialog to print that new window. I am using the following to accomplish this:

var w = window.open();
w.document.write(html);
w.document.close();

Where html contains:

...<body onload="window.print()">...</body>...

This all works, the window pops up, and the print dialog is shown for the new page, however, for some reason the browser isn't waiting for all the images on the page to load before showing the print dialog. It's causing some images not to print.

There are many images, and they are dynamically generated on the server side (takes about 1 sec each to load). How do I force the browser to only print once all the images are loaded?

This happens in Chrome and Firefox that I've confirmed. I appreciate any help.

解决方案

Try putting your printer call in an onload event for the last image.

<img onload="window.print()" ... />

EDIT:

Full answer by OP as seen below:

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中打印弹出窗口缺失图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆