gpt4 book ai didi

javascript - 允许在打印前格式化窗口

转载 作者:行者123 更新时间:2023-12-03 11:47:18 27 4
gpt4 key购买 nike

我使用下面的 JavaScript 代码将元素 ID 传递给方法,然后该方法将在单独的窗口中格式化该特定 ID,然后进行打印。我遇到的问题是,在窗口完成格式化新页面之前,打印对话框已打开。然后我必须取消打印对话框,然后允许页面格式化,然后再次启动打印。如何确保页面在打印对话框打开之前完成格式化?谢谢。

function printPartOfPage(elementId) {   
var printHeader = document.getElementById('header');
var printContent = document.getElementById(elementId);
var windowUrl = 'NewWindow';
var uniqueName = new Date();
var windowName = 'Print' + uniqueName.getTime();
var printWindow = window.open(windowUrl, windowName, 'left=20,top=200');
printWindow.document.write('<html xmlns="http://www.w3.org/1999/xhtml"><head>');
printWindow.document.write('<link href='+sURL+'css/style.css rel="stylesheet">');
printWindow.document.write('<link href='+sURL+'css/print.css rel="stylesheet">');
printWindow.document.write('</head><body>');
printWindow.document.write(printContent.innerHTML);
printWindow.document.write('</body></html>');
printWindow.document.close();
printWindow.focus();
printWindow.print();
}

最佳答案

您可以使用setTimeout在页面格式之后打印几毫秒。

...
setTimeout(function(){
printWindow.print();
}, 1)

或者,您可以等待窗口完成加载:

printWindow.document.addEventListener('load', function(){
printWindow.print();
})

关于javascript - 允许在打印前格式化窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25997305/

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