使用 JavaScript 和 Google Chrome 创建并打开新窗口并打印图像

A. *_*nis 3 html javascript css google-chrome

JavaScript当我尝试使用的 window.print()打开并打印窗口时,Chrome打印时图像不会显示在 , 中。我的代码如下:

<html>
<head>
<script type="text/javascript">
  function openWin()
  {
    var myWindow = window.open('','', 'width=200,height=100');

    myWindow.document.write("<p>This is 'myWindow'</p>");
    myWindow.document.write("<p><img src='https://www.google.gr/images/srpr/logo11w.png' width='400' /></p>");

    myWindow.document.close();
    myWindow.focus();
    myWindow.print();
    myWindow.close();

 }
</script>
</head>
<body>

<input type="button" value="Open window" onclick="openWin()" />

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

你可以在这里查看http://jsfiddle.net/Q5Xc9/649/ 如何解决这个问题?

joh*_*rdy 5

调用时图像尚未加载print()。

您需要延迟调用,print直到图像加载完成后。jQuery 可以做到这一点,因此您可以在页面中包含 jquery,然后将调用包装print在如下代码中:

function openWin()
{
    var myWindow = window.open('','','width=500,height=500');
    myWindow.document.write("<p>This is 'myWindow'</p>");
    myWindow.document.write("<p><img src='https://www.google.gr/images/srpr/logo11w.png' width='400' /> </p>");

    myWindow.document.write("<script src='http://code.jquery.com/jquery-1.10.1.min.js'></script>");
    myWindow.document.write("<script>$(window).load(function(){ print(); });</script>");
}
Run Code Online (Sandbox Code Playgroud)