gpt4 book ai didi

javascript - 使用 Javascript 在 Chrome 中打印图像

转载 作者:行者123 更新时间:2023-11-28 07:40:04 28 4
gpt4 key购买 nike

在我的网站上,我想创建用于打印各种图像的按钮。我知道这可以使用 Javascript 来实现。经过一番研究,我写了这个:

<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')">

这会在新选项卡中打开图像,但不会显示打印对话框。我做错了什么?

进一步的研究得出了不同的方法:

<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')">

这给了我一个奇怪的结果。当尝试打印小图像时,打印对话框会按预期弹出。但是当我尝试打印更大的图像(覆盖整张 A4 纸)时,对话框不会弹出。到底发生了什么事?

考虑到我希望实现的目标,你们认为最好的方法是什么?

提前致谢!

编辑

这实际上似乎是一个与浏览器相关的问题。上面的代码在 Firefox 和 IE 中运行得很好。我遇到这个问题是因为我正在 Chrome 中开发网站。显然 Chrome 不会在显示打印窗口之前等待我的窗口内容加载。其他浏览器似乎都是先等待内容加载,然后显示打印窗口。我当然尝试过 setTimeout 函数但没有成功。因此,我的问题是,有人可以告诉我在 Chrome 中打印图像的解决方法吗?

已解决

这个网站被证明是黄金网站:http://nice-tutorials.blogspot.se/2014/01/image-printing-problem-in-google-chrome.html

问题解决了!

最佳答案

解决办法是在body标签中添加onLoad事件:

printWindow.document.write('</head><body onLoad="self.print(); self.close()"><img src=\'');

关于javascript - 使用 Javascript 在 Chrome 中打印图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28159690/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com