簡體   English   中英

使用Javascript打印(部分)網頁

[英]Printing a (part of) webpage with Javascript

我知道有兩種方法可以調用瀏覽器的“打印”對話框(我當然使用了搜索):

  • document.print()
  • document.execCommand('print',false,null)

他們之間有什么區別? 跨瀏覽器支持? 論文,文檔或標准? 哪個更正確?

另一個問題:打印給定網頁部分的最直接方式是什么? 我知道我們可以創建新窗口或iframe來調用上面的兩種打印方法中的任何一種。 哪一個陷阱較少?

我已經測試了跨瀏覽器打印部分網頁的不同方式:Chrome,Firefox,Opera(12和新),IE11,10,9和8.我試圖創建新window ,新iframe或使用existing iframe這頁紙。 然后嘗試了.print().execCommand('print')

注意:請記住,在窗口上調用.print(),並在文檔上調用.execCommand()

用於測試的代碼可以在這里找到

如果我的測試代碼錯誤,請糾正我,我只是想找到最清楚的方法來完成這項工作。 我的結論:

  • Opera 12無法打印網頁的一部分(?)
  • IE不print() iframe和窗口,當前窗口除外。
  • 在iframe中的documents上調用print()或在IE中創建窗口會破壞當前document上的print() 小心!
  • jQuery插件printThis使用IE的技巧來完成這項工作,它只是起作用。 唯一的例外是Opera 12.順便說一句,這個插件使用print()
  • execCommand('print')幾乎可以在任何地方使用任何方法(iframe,window)。 但它並不支持Firefox。
  • 如果調用不成功, execCommand()將返回false ,因此如果您不想使用插件和魔術,創建窗口或iframe,請調用execCommand('print') ,如果返回false ,則調用print()

還有一件事:

創建iframe很棘手:您無法直接訪問其窗口文檔 (是的,您有ContentDocument屬性,它在瀏覽器中的行為不同)。 您應該命名它,然后調用window.frames[name]從該iframe獲取窗口對象。 不要試圖調用window.frames(id) - 它將返回iframe

然后,在接受的答案中提到的最后一種方法最終看起來像這樣:

iframe = document.getElementById('iframe-id');
var printed = iframe.contentWindow.document.execCommand('print', false, null);

if (!printed) window.print();

替代方案:

try {
    iframe = document.getElementById('iframe-id');
    iframe.contentWindow.document.execCommand('print', false, null);
}
catch(e) {
    window.print();
}

printThis使用的類似方法

if (document.queryCommandSupported("print")) {
    $iframe[0].contentWindow.print();
    $iframe[0].contentWindow.document.execCommand("print", false, null);
} else {
    $iframe[0].contentWindow.focus();
    $iframe[0].contentWindow.print();
}

您可以使用window.open和execComand的組合(saveas例如:

<script  type= "text/javascript">
 function saveas() {
  var oPrntWin = window.open("","_blank","width=1,height=1,left=1,top=1,menubar=yes,toolbar=yes,resizable=yes,location=no,scrollbars=yes");
  oPrntWin.document.open();
  oPrntWin.document.write(editeur.innerHTML);
  oPrntWin .document.execCommand("SaveAs",true,"C:\\My Documents\\Saved Content.html");
 oPrntWin.document.close();
 }
 </script> 

editeur.html是我的文檔的一部分,你可以為你的框架做同樣的替換新窗口中的文字由屬性“src”為身體

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM