使用Javascript在Chrome中打印图像
在我的网站上,我想创建用于打印各种图像的按钮。我知道这可以通过Javascript实现。经过一些研究,我写了这样一篇文章:使用Javascript在Chrome中打印图像,javascript,google-chrome,printing,Javascript,Google Chrome,Printing,在我的网站上,我想创建用于打印各种图像的按钮。我知道这可以通过Javascript实现。经过一些研究,我写了这样一篇文章: <script type="text/javascript"> var pwin; function printImg(imgSrc) { pwin = window.open(imgSrc, "_blank"); setTimeout("pwin.print()", 20); } </script> ... <input cl
<script type="text/javascript">
var pwin;
function printImg(imgSrc) {
pwin = window.open(imgSrc, "_blank");
setTimeout("pwin.print()", 20);
}
</script>
...
<input class="printAndSolve" type="submit" value="Print"
onclick="printImg('original.png')">
var pwin;
函数printImg(imgSrc){
pwin=窗口打开(imgSrc,“_blank”);
setTimeout(“pwin.print()”,20);
}
...
这将在新选项卡中打开图像,但不会显示“打印”对话框。
我做错了什么
进一步的研究产生了一种不同的方法:
<script type="text/javascript">
function printImg(imgSrc) {
var printWindow = window.open('', 'Print
Window','height=400,width=600');
printWindow.document.write('<html><head><title>Print Window</title>');
printWindow.document.write('</head><body ><img src=\'');
printWindow.document.write(imgSrc);
printWindow.document.write('\' /></body></html>');
printWindow.document.close();
printWindow.onload = function() { printWindow.print(); };
}
</script>
...
<input class="printAndSolve" type="submit" value="Print"
onclick="printImg('original.png')">
函数printImg(imgSrc){
var printWindow=window.open(“”,'打印
窗口','高度=400,宽度=600';
printWindow.document.write('Print Window');
printWindow.document.write(“”);
printWindow.document.close();
printWindow.onload=函数(){printWindow.print();};
}
...
这给了我一个奇怪的结果。当尝试打印小图像时,会弹出打印对话框。但是当我试图打印一张更大的图像(覆盖一整张A4纸)时,对话框不会弹出。到底发生了什么事
考虑到我希望实现的目标,你们认为什么是最好的方法
提前谢谢
编辑
这实际上似乎是一个与浏览器相关的问题。上面的代码在Firefox和IE中运行得非常好。我遇到这个问题是因为我正在用Chrome开发网站。显然Chrome不会等到我的窗口内容加载后才显示打印窗口。其他浏览器似乎都是先等待内容加载,然后显示打印窗口。
我当然尝试过setTimeout函数,但没有成功。
因此,我的问题是,有人能给我一个在Chrome上打印图像的解决方案吗
已解决
该网站被证明是黄金:
问题解决了 解决方案是将onLoad事件添加到body标记:
printWindow.document.write('</head><body onLoad="self.print(); self.close()"><img src=\'');
printWindow.document.write('