在通过child.print()打印之前,如何在新窗口中等待图像加载?

时间:2012-09-10 20:43:16

标签: javascript printing popup parent-child onload

    $("#print").on('click', function () {
        var child = window.open("image.jpg", "_blank", "location=0,toolbar=0,scrollbars=1,fullscreen=1,menubar=0");
        //any way to know/wait for image to load?
        child.print();
    });

在调用.print()之前,我的父窗口知道子窗口是否已完成加载图像的任何方法?如果他们感到高兴,他们最终会打印一个空白页面。

我试过了两个:

child.attachEvent("onload", function () { child.print(); });

child.attachEvent("DOMContentLoaded", function () { child.print(); });
//(found this online, apparently it's Firefox only, still didn't work)

1 个答案:

答案 0 :(得分:1)

您需要创建一个页面,即print.html并将此脚本添加到其中:

<html>
<head>
</head>
<body>
<script>
(function( w, d ) {
    var paramsHash = {},
        img = new Image(); 

    (function() {
        var qs = w.location.href.split( '?' )[ 1 ],
            items = [],
            l = 0,
            i = 0,
            param;
        if( qs && qs.indexOf( '&' ) ) {
            items = qs.split( '&' );
        } else {
            items = [ qs ];
        }
        l = items.length;
        for( ; i < l; i++ ) {
            param = items[i].split( '=' );
            paramsHash[ param[ 0 ] ] = param[ 1 ];
        }
    })();
    console.log(paramsHash);
    img.src = paramsHash.img;
    //after the image is loaded, call this function
    img.onload = function() {
        window.print();        
    };
    d.body.appendChild( img );

})( window, document );
</script>
</body>
</html>

然后像这样使用它:

$("#print").on('click', function () {
    window.open("print.html?img=image.jpg", "_blank", "location=0,toolbar=0,scrollbars=1,fullscreen=1,menubar=0");
    });