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

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

Thuộc tính sự kiện onbeforeprint được kích hoạt khi trang sắp được in hoặc trước khi hộp thoại in xuất hiện.

Cú pháp

<tagname onbeforeprint="script"></tagname>

Ví dụ

Thay đổi nền trang trước khi in:

<!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 onbeforeprint="beforePrint()">
<h1>Demo onbeforeprint</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 beforePrint() {
    document.body.style.background = "lightblue";
    document.querySelector('.show').innerHTML = '<p>Sự kiện onbeforeprint đã kích hoạt</p>';
  }
</script>
</body>
</html>

Kết quả

Nhấn Ctrl+P để mở hộp thoại in → nền trang thay đổi thành xanh nhạt trước khi in.

Ứng dụng: Thường dùng để ẩn các phần tử không cần in (menu, quảng cáo) hoặc điều chỉnh layout cho bản in.