javascript - 在缺少图像的 JavaScript 中打印弹出窗口

标签 javascript html browser printing cross-browser

我想打开一个新窗口/选项卡,在文档中放入一些 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/

相关文章:

Javascript import myClass from '/myClass.js' 在浏览器中不起作用

javascript - 如果 Windows 上的条件加载在 javascript 中不起作用

javascript - django 提供的index.html 无法找到socket.io 服务器

javascript - JavaScript 中的 new String ("x") 有什么意义?

javascript - 更改 location.hash 然后按返回按钮 - IE 的行为与其他浏览器不同

java - 如何调试 ERR_SSL_PROTOCOL_ERROR/SSL_ERROR_RX_RECORD_TOO_LONG?

javascript - 循环遍历数组并过滤电子邮件

javascript - 如何将样式应用于表格中的偶数或奇数行?

javascript - 在 CSS 过渡期间显示元素的大小值

javascript - 元素的简单 HTML5 键盘导航