@media print {
/* 隱藏導航、廣告、按鈕 */
.no-print { display: none !important; }
/* 重置背景、色彩,節省墨水 */
body { background: #fff !important; color: #000 !important; }
a { text-decoration: none; color: #000; }
a[href^="http"]::after { content: " (" attr(href) ")"; font-size: 0.8em; }
/* 分頁控制 */
.page-break-before { page-break-before: always; }
.page-break-after { page-break-after: always; }
.page-break-inside-avoid { page-break-inside: avoid; }
/* 頁邊距 */
@page { margin: 2cm; size: A4 portrait; }
@page :first { margin-top: 3cm; } /* 首頁較大上邊距 */
/* 表格跨頁重複表頭 */
thead { display: table-header-group; }
tr { page-break-inside: avoid; }
/* 字體大小調整 */
h1 { font-size: 1.5rem; }
h2 { font-size: 1.25rem; }
}
function printPage() {
window.print(); // 開啟列印對話框
// 列印完成/取消無回調,若需追蹤可用 beforeprint/afterprint 事件
}
window.addEventListener('beforeprint', () => document.body.classList.add('printing'));
window.addEventListener('afterprint', () => document.body.classList.remove('printing'));
| 問題 | 解法 |
|---|---|
| 背景色/圖不列印 | 瀏覽器設定「列印背景圖形」或改用 `border`/`box-shadow` 模擬 |
| Flex/Grid 佈局分頁錯亂 | 關鍵區塊改用 `display:block` 或 `table`,避免跨頁斷裂 |
| 固定定位元素重複出現 | 列印媒體下 `position: static` 或 `display:none` |
| 頁碼/日期由瀏覽器自動加入 | 無法移除,設計時預留邊距空間 |