function printHtml(html) {
var bodyHtml = document.body.innerHTML; // 備份整頁
document.body.innerHTML = html; // 替換為打印區域
window.print(); // 唤起打印對話框
document.body.innerHTML = bodyHtml; // 還原
// 注意:還原後所有事件綁定、組件實例均失效,需重新初始化
}
function onPrint() {
var html = $('#printArea').html();
printHtml(html);
}
缺點:破壞頁面狀態、事件丟失、重繞流重繪、單頁應用災難。
<style>
@media print {
.no-print { display: none !important; }
.print-only { display: block !important; }
body { margin: 0; background: white; }
#printArea { width: 100%; }
}
</style>
<button onclick="window.print()">打印</button>
<div class="no-print">導航/側邊欄/廣告...</div>
<div id="printArea" class="print-only">核心打印內容</div>
優勢:零 JS 破壞、瀏覽器原生分頁/頁眉頁腳、樣式完全可控、性能最佳。
function printIframe(content, cssUrl) {
var iframe = document.createElement('iframe');
iframe.style.cssText = 'position:absolute;left:-9999px;top:-9999px;';
document.body.appendChild(iframe);
var doc = iframe.contentWindow.document;
doc.open();
doc.write('<html><head><link rel="stylesheet" href="' + cssUrl + '"></head><body>' + content + '</body></html>');
doc.close();
iframe.contentWindow.focus();
iframe.contentWindow.print();
setTimeout(() => document.body.removeChild(iframe), 1000);
}
// 使用
$('#btnPrint').click(function() {
printIframe($('#printArea').html(), '/css/print.css');
});
pt/cm/mm,避免 pxpage-break-inside: avoid 防止表格/卡片跨頁斷裂@page { margin: 2cm; size: A4; } 設置頁邊距/紙張| 方案 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| innerHTML 替換 | 代碼極少 | 破壞頁面狀態、事件丟失、SPA 禁用 | 極簡靜態頁、快速原型 |
| @media print | 標準、無副作用、性能最好 | 需預先寫好打印樣式 | **所有現代項目首選** |
| iframe 隔離 | 樣式隔離、不影響主頁、支援不同 CSS | 跨域受限、iframe 載入延遲 | 需完全不同佈局、舊 IE 兼容 |