萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 實現區塊列印:指定區域列印與排除區域

需求背景

網頁列印時,往往只需列印特定區塊(如報表、憑證),並排除導覽列、廣告、按鈕等非必要內容。本文介紹「區塊包裹 + CSS 排除 + JS 替換 body」的完整方案。

HTML 結構規劃

<!-- 需列印區塊 -->
<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>

CSS 列印媒體查詢

<style type="text/css" media="print">
  .noprint { display: none !important; } /* 或 visibility: hidden; */
  /* 可加入列印專用樣式:頁邊距、字體大小等 */
  @page { margin: 2cm; }
  body { font-size: 12pt; }
</style>

JS 列印邏輯(核心:替換 body.innerHTML)

$(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 架構
  }
});

關鍵點與坑點

  1. 樣式遺失:替換 body.innerHTML 會導致原有 <link>、<style> 消失,必須在目標區塊內重新注入 CSS。
  2. 事件綁定失效:恢復 innerHTML 後,原有 jQuery 事件、Vue/React 元件皆失效。單頁應用建議改用 iframe 或新視窗列印。
  3. iframe 替代方案:建立隱藏 iframe,將列印內容寫入 iframe.document,呼叫 iframe.contentWindow.print(),不影響主頁面狀態。
  4. iframe 列印範例(推薦現代專案使用)

    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);
      };
    }
    
copyright © 萬盛學電腦網 all rights reserved