javascript - 让 window.print 等到窗口加载完毕

标签 javascript html

我需要打印一个用 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/

相关文章:

html - CSS div 不改变高度以适应更大的子 div

javascript - 使用来自 JS 对象的数据填充数据表

javascript - 在 JavaScript 中创建派生类的多个实例

javascript - 使用 jquery 在选中/未选中的复选框上添加/删除值

javascript - 更改数组内对象属性名称的值

javascript - 如果没有类名则隐藏 div

css - 在 html 页面的左右两侧添加两条垂直线(矩形)

html - 在边框 css 上显示文本

jquery - 如何从所有子元素中删除类

html - 仅在菜单栏上填充左文本