Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> HTML

Thực thi script trước khi in tài liệu (onbeforeprint) trong HTML?

Sự kiện onbeforeprint kích hoạt ngay trước khi hộp thoại in xuất hiện (người dùng nhấn Ctrl+P hoặc window.print()). Dùng để: điều chỉnh layout in, ẩn phần tử, thêm watermark, cập nhật số trang.

Ví dụ

<!DOCTYPE html>
<html>
  <body onbeforeprint="display()">
    <script>
      function display() {
        alert("Tài liệu sắp được in.");
        // document.body.classList.add('printing');
      }
    </script>
  </body>
</html>

Cách hiện đại

window.addEventListener('beforeprint', () => {
  document.body.classList.add('printing');
  // Cập nhật số trang, ẩn sidebar, thêm header/footer in...
});

window.addEventListener('afterprint', () => {
  document.body.classList.remove('printing');
});

CSS @media print (khuyên dùng hơn)

@media print {
  .no-print { display: none !important; }
  .only-print { display: block !important; }
  body { font-size: 12pt; color: #000; }
  a::after { content: " (" attr(href) ")"; } /* In URL link */
}

Lưu ý

  • onbeforeprint / onafterprint hỗ trợ tốt trên desktop, yếu trên mobile.
  • Ưu tiên CSS @media print — không phụ thuộc JS, tin cậy hơn.