Home  >  Article  >  Web Front-end  >  ✨ Simple trick for printing a div

✨ Simple trick for printing a div

WBOY
WBOYOriginal
2024-08-02 04:25:02717browse

✨ Simple trick for printing a div

Advantages

  • Your page retains interactivity after print
  • Plays nice with frameworks
  • Doesn't require duplicating your UI for print

Steps

  1. Hide every content of the page when in print mode
  2. Make your target element visible in print mode

Step 1

@media print {
  body {
    visibility: hidden;
  }
}

Step 2

@media print {
  #section-to-print {
    top: 0;
    left: 0;
    position: absolute;
    visibility: visible;
  }
}

Then print

const button = document.querySelector('print-page');

button.addEventListener('click', () => window.print());

This method avoids the pitfall of loosing interactivity, other methods replace the entire page content with the static HTML thereby loosing interactivity.

const printContents = document.getElementById(divId).innerHTML;
const originalContents = document.body.innerHTML;

document.body.innerHTML = printContents;

window.print();

document.body.innerHTML = originalContents;

The above is the detailed content of ✨ Simple trick for printing a div. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Glamup Cricket WebsiteNext article:Glamup Cricket Website