2012-09-10 14 views
1
$("#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.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

您將需要創建一個頁面,即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"); 
    }); 
+0

很感謝,我也有這樣的想法,猜想沒有辦法避免它。 – BigOmega

相關問題