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

Thuộc tính sự kiện onafterprint trong HTML

Thuộc tính sự kiện onafterprint được kích hoạt khi trang đã bắt đầu in hoặc hộp thoại in đã được đóng.

Cú pháp

<tagname onafterprint="script"></tagname>

Ví dụ

Khôi phục giao diện sau khi in xong:

<!DOCTYPE html>
<html>
<head>
<style>
  body {
    color: #000;
    height: 100vh;
    background-color: #FBAB7E;
    background-image: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%);
    text-align: center;
    padding: 20px;
  }
  p { font-size: 1.1rem; }
</style>
</head>
<body onafterprint="afterPrint()">
<h1>Demo onafterprint</h1>
<p>Tôi là một đoạn văn bản HTML.</p>
<p style="color:#db133a;">Hãy thử in tài liệu này (Ctrl+P).</p>
<div class="show"></div>
<script>
  function afterPrint() {
    document.body.style.background = "linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%)";
    document.querySelector('.show').innerHTML = '<p>Sự kiện onafterprint đã kích hoạt - đã khôi phục giao diện</p>';
  }
</script>
</body>
</html>

Kết quả

Nhấn Ctrl+P, sau đó đóng hộp thoại in hoặc hoàn tất in → giao diện khôi phục lại trạng thái ban đầu.

Cặp đôi: onbeforeprint (trước in) + onafterprint (sau in) để quản lý trạng thái trang khi in.