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

3
当我尝试使用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>

你可以在这里查看 http://jsfiddle.net/Q5Xc9/649/

怎样解决这个问题?

1个回答

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>");
}

在哪里添加我的窗口名称?“myWindow”?还是不需要? - A. Zalonis
我已经编辑了我的回答。试一下吧。JSFiddle不支持document.write,所以不要在那里尝试它 :-) - johnnycardy
这里 http://jsfiddle.net/Q5Xc9/685/ 起初可以运行,但只有第一次。需要重新加载才能再次运行。 - A. Zalonis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接