Javascript print()尝试在页面完成渲染之前打印页面(动态创建)

Javascript print()尝试在页面完成渲染之前打印页面(动态创建),javascript,settimeout,synchronous,Javascript,Settimeout,Synchronous,我正在尝试在新窗口中打印表格。 问题是,print在呈现页面之前尝试打印。 我怀疑文档。写入是异步的。 我尝试使用document.outerHTML/document.innerHTML而不是document.write(),但是CSS/JS文件没有被正确地解析为CSS。 该表的单元格中包含从缓存加载的图像,也在window.print()之后 拜托,任何想法都会有帮助的 函数printData(){ 让newWin=window.open(“”); 样式=”; //阅读不同页面中的样式 A

我正在尝试在新窗口中打印表格。 问题是,
print
在呈现页面之前尝试打印。 我怀疑
文档。写入
是异步的。
我尝试使用
document.outerHTML
/
document.innerHTML
而不是
document.write()
,但是CSS/JS文件没有被正确地解析为CSS。 该表的单元格中包含从缓存加载的图像,也在
window.print()
之后

拜托,任何想法都会有帮助的

函数printData(){
让newWin=window.open(“”);
样式=”;
//阅读不同页面中的样式
Array.prototype.forEach.call(
document.queryselectoral(“链接,样式”),
功能(el){
样式+=(el.outerHTML);
});
//不工作不渲染样式
//newWin.document.document.querySelector(“html”).innerHTML=(样式+document.querySelector(“table”).outerHTML);
//这将在打印后完成渲染
newWin.document.write(样式+文档.querySelector(“表”).outerHTML);
//不起作用
newWin.document.addEventListener(“DOMContentLoaded”,function()){
if(newWin.document.addEventListener==“加载”){
newWin.print();
}
//不起作用
newWin.window.onload=函数(){
newWin.print();
}
//工作
setTimeout(函数(){
newWin.print();
newWin.close();
}, 2000);
});
}
用于启动您的函数,因为这将等待页面的所有内容加载,并得到广泛支持

试试以下方法:

let printAndClose = '<script>onload = function() { window.print(); window.close(); }</sc' + 'ript>';

newWin.document.write(
  styles +
  document.querySelector("table").outerHTML) +
  printAndClose
);
let printAndClose='onload=function(){window.print();window.close();}';
newWin.document.write(
风格+
document.querySelector(“表”).outerHTML)+
打印关闭
);

我通过在
末尾添加以下代码解决了类似问题。它适用于IE11、Chrome和Firefox。调用
window.close()
而不在
setTimeout()
中换行,会导致IE11在显示打印对话框之前关闭窗口

<script type="text/javascript">
    setTimeout(function() {
        window.print();
        setTimeout(function() {window.close();});
    });
</script>

setTimeout(函数(){
window.print();
setTimeout(函数(){window.close();});
});

这里有一个异国情调:为所有图像附加一个onload函数。它要做的第一件事是将触发图像的属性“done”设置为“true”。然后在所有未完成的图像上选择:$('img[done!=“true”])。如果长度为0,则打印。我尝试删除所有图像,但仍然没有我正在使用它//不起作用newWin.window.onload=function(){newWin.print();}非常好的想法:我尝试了,但不起作用,但我成功地使用let print and close='window.print();window.close();';非常感谢,您知道document.write()的行为为何是异步的吗?
document.write可以多次调用,以从片段构建文档。没有对
文档的隐式调用。请关闭
,因此。。。这就指向了另一种可能的解决方案:在调用
newWin.print()
之前,您可以显式调用
newWin.document.close()
…谢谢!!我正要问一个问题,突然发现了这个解决方案。