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

标签 javascript getelementbyid

我使用下面的 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/

相关文章:

javascript - 将变量分配给 img src

javascript - 创建音量条 javascript

javascript - 如何在 JavaScript 中根据 "before"和 "after"条件对数组进行排序?

javascript - 在 Powershell 中在此对象上找不到属性 'value'

javascript - 如何检查 DOM 中 div 的所有类名是否具有带有 vanilla Javascript 的特定字符串?

Javascript getElementByID 方法

javascript - 它说 TypeError : document. getElementById(...) 为 null

javascript - 动态添加文本区域到容器extjs

javascript - 类型错误 : K is undefined

javascript - 我想通过文本输入从用户那里获取两个整数,找到两个数字之间的差值并将该数字除以 25。我该怎么做?