文章出處
View Code
View Code
View Code
View Code
文章列表
錯誤的寫法:

//打印 function printPage(areaId) { if (parent.$("#PrinFrame").length == 0) { parent.$("body").append('<iframe id="PrinFrame" style="display: none; "></iframe>'); } var prinFrame = parent.$("#PrinFrame")[0]; $(prinFrame).contents().find("body").html($("#" + areaId).html()); var win = prinFrame.contentWindow; win.document.execCommand('Print'); }
錯誤原因:只把打印區域的內容放到iframe中,樣式信息丟了。
改進后的寫法:

//打印 function printPage(areaId) { if (parent.$("#PrinFrame").length == 0) { parent.$("body").append('<iframe id="PrinFrame" style="display: none; "></iframe>'); } var prinFrame = parent.$("#PrinFrame")[0]; var win = prinFrame.contentWindow; $(prinFrame).attr("src", window.location.href); $(prinFrame).load(function () { $(prinFrame).contents().find("body").html($("#" + areaId).html()); win.document.execCommand('Print'); }); }
在iframe中重新加載當前頁面,然后把body中的內容替換成待打印區域,這樣iframe中保留了樣式信息。
上面寫法的缺點:多次點擊打印按鈕,iframe的load事件會被綁定多次;打印區域的大小超出A4紙范圍;
再次改進后的寫法:

//打印 function printPage(areaId) { var prinFrame; var win; if (parent.$("#PrinFrame").length == 0) { parent.$("body").append('<iframe id="PrinFrame" style="display: none; "></iframe>'); prinFrame = parent.$("#PrinFrame")[0]; win = prinFrame.contentWindow; $(prinFrame).load(function () { setTimeout(function () { var html = '<table style="width:970px;"><tr><td>'; html += $("#" + areaId).html(); html += '</td></tr></table>'; $(prinFrame).contents().find("body").html(html); win.document.execCommand('Print'); }, 100); }); } else { prinFrame = parent.$("#PrinFrame")[0]; } $(prinFrame).attr("src", window.location.href); }
再次改進后,確保iframe的load事件只被綁定一次;用寬度為970的table限制打印區域大小。
上面的寫法還是有錯誤,重新打開tab頁時,點擊打印,不再進入iframe的load方法,再修改:

//打印 function printPage(areaId) { if (parent.$("#PrinFrame").length == 0) { parent.$("body").append('<iframe id="PrinFrame" style="display: none; "></iframe>'); } parent.$("#PrinFrame").attr("src", window.location.href); parent.$("#PrinFrame").one("load", function () { setTimeout(function () { var html = '<table style="width:970px;"><tr><td>'; html += $("#" + areaId).html(); html += '</td></tr></table>'; parent.$("#PrinFrame").contents().find("body").html(html); parent.$("#PrinFrame")[0].contentWindow.document.execCommand('Print'); }, 100); }); }
弄了一天,分頁打印的時候還是有問題,如下圖:
文章列表
全站熱搜