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

Thực thi script sau khi in xong tài liệu (onafterprint) trong HTML?

Sự kiện onafterprint kích hoạt sau khi hộp thoại in đóng (người dùng in xong hoặc hủy). Dùng để: khôi phục layout, xóa watermark, ghi log, bật lại UI bị ẩn khi in.

Ví dụ

<!DOCTYPE html>
<html>
  <body onafterprint="display()">
    <script>
      function display() {
        alert("In xong hoặc hủy in!");
        // document.body.classList.remove('printing');
      }
    </script>
  </body>
</html>

Cặp sự kiện in

Sự kiện Thời điểm Dùng cho
beforeprintTrước khi mở hộp thoại inChuẩn bị layout in, ẩn sidebar, thêm header/footer
afterprintSau khi đóng hộp thoại inKhôi phục layout, cleanup

Cách hiện đại

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

CSS @media print (khuyên dùng chính)

@media print {
  .sidebar, .nav, .ads, .no-print { display: none !important; }
  .content { width: 100%; margin: 0; }
  a::after { content: " (" attr(href) ")"; font-size: 0.8em; color: #666; }
  @page { margin: 2cm; } /* Margin trang in */
}

Lưu ý

  • Mobile: hỗ trợ yếu, ưu tiên CSS print.
  • afterprint cũng chạy khi user hủy in (Esc/Cancel).