,我與所有在IE8上述解決方案的問題,已經發現,在IE 8測試一個體面的解決辦法+9,Chrome,Safari和Firefox。對於我的情況,我需要打印是動態生成的報告:
// create content of iframe
var content = '<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">'+
'<head><link href="/css/print.css" media="all" rel="stylesheet" type="text/css"></head>'+
'<body>(rest of body content)'+
'<script type="text/javascript">function printPage() { window.focus(); window.print();return; }</script>'+
'</body></html>';
注意的PrintPage()前身體JavaScript方法結束標記。
下一頁創建iframe和其附加到母體所以其contentWindow可用:
var newIframe = document.createElement('iframe');
newIframe.width = '0';
newIframe.height = '0';
newIframe.src = 'about:blank';
document.body.appendChild(newIframe);
下一頁設置內容:
newIframe.contentWindow.contents = content;
newIframe.src = 'javascript:window["contents"]';
在這裏我們使用動態內容變量的iframe的窗口對象然後通過javascript:scheme調用它。
最後打印;專注於iframe和調用iframe中的內容在JavaScript的PrintPage()函數:
newIframe.focus();
setTimeout(function() {
newIframe.contentWindow.printPage();
}, 200);
return;
不是必需的setTimeout的,但是如果你裝載大量的內容,我發現鉻偶爾失敗,沒有它打印等等建議這一步。另一種方法是將'newIframe.contentWindow.printPage();'在try catch中並將setTimeout包裝的版本放在catch塊中。
希望這可以幫助別人,因爲我花了很多時間找到可以在多個瀏覽器上運行良好的解決方案。感謝SpareCycles。
編輯:
使用的setTimeout來調用的PrintPage功能使用以下代替:
newIframe.onload = function() {
newIframe.contentWindow.printPage();
}
是同一個域上的父頁面和框架頁面? – 2012-03-08 10:49:36
是的,其實iframe是空的我正在寫內容 – user1083382 2012-03-08 10:51:28