我需要打印一个用 JavaScript 和 Html 动态创建的页面。我的问题是有时它显示空白页。我认为这是因为“窗口”尚未加载。打印怎么能等到窗口加载完?
我尝试添加方法 wait()
但问题是一样的。
这是打印页面的方法:
function printpage(){
var panel;
panel =document.getElementById("cajaticket").innerHTML;
var mywindow = window.open('', 'Print');
mywindow.document.write('<html><head><link rel="stylesheet" href="css/extras/ticket.css"></head><body>');
mywindow.document.write(panel);
mywindow.document.write('</body></html>');
mywindow.document.close();
mywindow.focus();
mywindow.print();
mywindow.close();
panel=null;
}
它应该总是打印窗口,但目前,它只是有时有效。
最佳答案
如果你需要 jQuery 来帮助你,试试这个:
$($(window).on('load', function() {
printpage();
});
);
function printpage(){
var panel;
panel =document.getElementById("cajaticket").innerHTML;
var mywindow = window.open('', 'Print');
mywindow.document.write('<html><head><link rel="stylesheet" href="css/extras/ticket.css"></head><body>');
mywindow.document.write(panel);
mywindow.document.write('</body></html>');
mywindow.focus();
mywindow.print();
mywindow.close();
panel=null;
}
这将确保 DOM
在打印前加载、准备好并呈现。
更新:使用
$(mywindow).on('load', function() {
// manipulate mywindow here
});
本来很好,但文档没有明确说明支持:
The load event is sent to an element when it and all sub-elements have been completely loaded. This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the
window
object.
查看完整文档 here .
关于javascript - 让 window.print 等到窗口加载完毕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57239632/