萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML 腳本教學

網頁列印預覽:局部內容隱藏與指定區塊列印的兩種方案

網頁列印時常需隱藏導航、廣告等非核心內容,或僅列印特定區塊。以下提供兩種 CSS 與 JS 結合的實用方案。

方案一:針對少量元素隱藏(不列印)

利用 @media print 媒體查詢,定義 .notprint 類別:

@media print {
  .notprint { display: none; }
}
@media screen {
  .notprint { display: inline; cursor: pointer; }
}

需隱藏的元素僅需加上 class="notprint" 即可。

方案二:僅列印指定區塊(獨立預覽頁)

建立專用預覽頁 review.htm,內嵌 WebBrowser ActiveX 控制項(僅 IE 支援),透過 window.open 呼叫:

<head>
  <object id="WebBrowser" classid="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2" width="0" height="0"></object>
  <style>
    @media print { .notprint { display: none; } }
    @media screen { .notprint { display: inline; cursor: pointer; } }
  </style>
</head>
<body></body>
<script>
  function window.onload() {
    var printArea = opener.document.all.printArea;
    window.document.body.innerHTML = printArea.innerHTML;
    window.focus();
    window.document.all.WebBrowser.ExecWB(7, 1); // 7=Print Preview, 1=Don't prompt
    window.close();
  }
</script>

主頁面將欲列印區域包裹於 <div id="printArea">...</div>,呼叫 window.open("review.htm") 即可彈出預覽視窗。

注意:此方案依賴 IE 專屬 ActiveX,現代跨瀏覽器專案建議改用 @media print 搭配 print.css 或列印專用樣式表。

copyright © 萬盛學電腦網 all rights reserved