我有一些代码来创建一个弹出窗口,编写一些 html 并打印。谷歌浏览器在打印预览中不显示图像,但其他浏览器工作正常。在我的案例中,文件 Logo_big.png
丢失了。我怎样才能让它在 Chrome 中也能正常工作?
我的代码:
var newWindow = window.open('', '', 'width=100, height=100'),
document = newWindow.document.open(),
pageContent =
'<!DOCTYPE html>' +
'<html>' +
'<head>' +
'<meta charset="utf-8" />' +
'<title>Inventory</title>' +
'<style type="text/css">body {-webkit-print-color-adjust: exact; font-family: Arial; }</style>' +
'</head>' +
'<body><div><div style="width:33.33%; float:left;"><img src="img/Logo_big.png"/></body></html>';
document.write(pageContent);
document.close();
newWindow.moveTo(0, 0);
newWindow.resizeTo(screen.width, screen.height);
newWindow.print();
newWindow.close();
最佳答案
这里的问题是 javascript 没有给 DOM 足够的(任何)时间来加载/渲染图像,一旦它设置了 src
。
您需要留出时间让浏览器加载/渲染(从缓存或其他方式)图像,您可以通过设置 setTimeout
来延迟从正在设置的内容打印。
这个具体问题的一个例子是:
var newWindow = window.open('', '', 'width=100, height=100'),
document = newWindow.document.open(),
pageContent =
'<!DOCTYPE html>' +
'<html>' +
'<head>' +
'<meta charset="utf-8" />' +
'<title>Inventory</title>' +
'<style type="text/css">body {-webkit-print-color-adjust: exact; font-family: Arial; }</style>' +
'</head>' +
'<body><div><div style="width:33.33%; float:left;"><img src="img/Logo_big.png"/></body></html>';
document.write(pageContent);
document.close();
newWindow.moveTo(0, 0);
newWindow.resizeTo(screen.width, screen.height);
setTimeout(function() {
newWindow.print();
newWindow.close();
}, 250);
setTimeout
设置得越低,浏览器加载图像所需的时间就越少,因此您需要对此进行调整,并在适用的情况下考虑较慢的互联网连接/浏览器。
关于javascript - 谷歌浏览器在打印预览中不显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31725373/