網頁列印時,往往只需列印特定區塊(如報表、憑證),並排除導覽列、廣告、按鈕等非必要內容。本文介紹「區塊包裹 + CSS 排除 + JS 替換 body」的完整方案。
<!-- 需列印區塊 -->
<div id="itemVrbjForm" style="font-family:'FangSong','SimSun'; font-size:18px; margin-top:290px;">
<div style="width:600px; margin:0 auto;">
<div style="float:right; margin-top:-40px;">(告知單編號:${zjxfItemUser.acceptedNo})</div>
<div id="title" style="margin-top:40px;"><span>信訪事項轉辦告知單</span></div>
${zjxfItemUser.userName}:(信訪人名稱)<br/>
<span id="itemVrbjTime"></span>,本機關依法受理...
<br/>特此告知。<br/>
<div style="margin-top:50px; margin-right:20px; float:right;">(蓋${zjxfProcessOver.subOrgname}專用章)</div>
<div style="margin-top:90px; margin-right:-190px; float:right;"><span id="itemVrbjEndTime"></span></div>
</div>
</div>
<!-- 不需列印區塊(加上 class="noprint") -->
<div class="noprint">
<button id="printBtn">列印</button>
<nav>...導覽列...</nav>
</div>
<style type="text/css" media="print">
.noprint { display: none !important; } /* 或 visibility: hidden; */
/* 可加入列印專用樣式:頁邊距、字體大小等 */
@page { margin: 2cm; }
body { font-size: 12pt; }
</style>
$(function() {
$("#printBtn").click(function() {
var originalHtml = document.body.innerHTML; // 備份原始頁面
exportCSS("itemVrbjForm", originalHtml);
});
function exportCSS(formName, htmlInfo) {
// 1. 注入必要 CSS(因 body 將被替換,原有 link 會失效)
var cssLinks = [
baseURL + '/zjxf/common/css/common.css',
baseURL + '/zjxf/common/css/table.css',
baseURL + '/zjxf/common/css/form.css',
baseURL + '/zjxf/common/css/tab.css',
baseURL + '/zjxf/common/css/print.css'
].map(function(href) {
return '<link href="' + href + '" type="text/css" rel="stylesheet" />';
}).join('');
$(cssLinks).appendTo("#" + formName);
// 2. 替換 body 為目標區塊內容
document.body.innerHTML = $("#" + formName).html();
// 3. 呼叫列印對話框
window.print();
// 4. 列印對話框關閉後恢復原頁面
document.body.innerHTML = htmlInfo;
// 注意:此時原有事件綁定已失效,需重新初始化或使用 SPA 架構
}
});
body.innerHTML 會導致原有 <link>、<style> 消失,必須在目標區塊內重新注入 CSS。innerHTML 後,原有 jQuery 事件、Vue/React 元件皆失效。單頁應用建議改用 iframe 或新視窗列印。iframe.contentWindow.print(),不影響主頁面狀態。function printSection(elementId) {
var iframe = document.createElement('iframe');
iframe.style.cssText = 'position:absolute; left:-9999px; top:-9999px;';
document.body.appendChild(iframe);
var doc = iframe.contentDocument || iframe.contentWindow.document;
var content = document.getElementById(elementId).outerHTML;
var styles = Array.from(document.querySelectorAll('link[rel="stylesheet"], style'))
.map(function(el) { return el.outerHTML; })
.join('');
doc.write('<!DOCTYPE html><html><head>' + styles + '</head><body>' + content + '</body></html>');
doc.close();
iframe.onload = function() {
iframe.contentWindow.focus();
iframe.contentWindow.print();
setTimeout(function() { document.body.removeChild(iframe); }, 1000);
};
}