Cli*_*ive 29 html javascript printing window
打开新窗口后,print()在IE中不起作用.它适用于Chrome.这是一个测试人员:
<html>
<head>
<script type="text/javascript">
function openWin()
{
myWindow=window.open('','','width=200,height=100');
myWindow.document.write("<p>This is 'myWindow'</p>");
myWindow.focus();
myWindow.print(); //DOES NOT WORK
}
</script>
</head>
<body>
<input type="button" value="Open window" onclick="openWin()" />
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
Osa*_*a E 14
图尔古特给出了正确的解决方案.为了清楚起见,您需要在写完后添加关闭.
function openWin()
{
myWindow=window.open('','','width=200,height=100');
myWindow.document.write("<p>This is 'myWindow'</p>");
myWindow.document.close(); //missing code
myWindow.focus();
myWindow.print();
}
Run Code Online (Sandbox Code Playgroud)
小智 5
<script type="text/javascript">
function printDiv(divName) {
var printContents = document.getElementById(divName).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
</script>
<div id="printableArea">CONTENT TO PRINT</div>
<input type="button" onclick="printDiv('printableArea')" value="Print Report" />
Run Code Online (Sandbox Code Playgroud)
由于大多数浏览器已更新,因此打印和关闭不再像以前那样有效。因此,您应该添加onafterprint事件侦听器以关闭打印窗口。
var printWindow = window.open('https://stackoverflow.com/');
printWindow.print();
//Close window once print is finished
printWindow.onafterprint = function(){
printWindow.close()
};
Run Code Online (Sandbox Code Playgroud)
小智 5
对我有用的是myWindow.document.close()在myWindow.document.write(). 这是我的解决方案,超时等待新窗口完成加载(如果您有很多要加载):
var win = window.open('', 'PrintWindow');
win.document.write('Stuff to print...');
setTimeout(function () {
win.document.close();
win.focus();
win.print();
win.close();
}, 1000);
Run Code Online (Sandbox Code Playgroud)