✨ Simple trick for printing a div

WBOY
Release: 2024-08-02 04:25:02
Original
608 people have browsed it

✨ 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; } }
Copy after login

Step 2

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

Then print

const button = document.querySelector('print-page'); button.addEventListener('click', () => window.print());
Copy after login

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;
Copy after login

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!

source:dev.to
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!