等待html写入窗口,然后调用window.print() [英] Wait for html to write to window before calling window.print()

查看:103
本文介绍了等待html写入窗口,然后调用window.print()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我附有此javascript代码,该代码将一些内容放入弹出窗口,然后尝试打印它:

I have this javascript code attached that puts some content into a popup window and then tries to print it:

$(".print_friendly_popup").click(function() {
    var target = $(this).data('print-target');
    var left = (screen.width/2)-(500/2);
    var top = (screen.height/2)-(500/2);
    var win = window.open("", "test", "width=500,height=500 top=" + top + ", left=" + left);

    if(target == 'review') {
        win.document.write($('#print_friendly_review').html());
    } else if(target == 'essay') {
        win.document.write($('#print_friendly_essay').html());
    }
    win.print();
    win.close();
});

问题是有时对win.document.write的调用花费的时间太长,并且窗口尝试打印空白屏幕.如何在启动打印之前等待window.document被写入?

The problem is sometimes the call to win.document.write takes too long and the window tries to print a blank screen. How do I wait for window.document to be written to before firing print?

推荐答案

那么呢:创建某种检查器"以查看窗口中是否包含内容,例如:

So how about this: create some sort of "checker" to see if the window has the content in it, for example:

var checkForContent = function () {
  setTimeout(function () {
    var content = win.document.querySelector('body').innerHTML

    if (content.length) {
      win.print()
      win.close()
    } else {
      checkForContent()
    }
  }, 200)
}

通过这种方式,您可以礼貌地等待内容在打印之前呈现.

This way you're politely waiting for the content to render before printing.

这篇关于等待html写入窗口,然后调用window.print()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆