Printing Specific HTML Content on Button Click Without Including Full Webpage
Printing only specific HTML content upon a user's button click can be achieved in various ways. One method is to create a hidden div element to hold the desired HTML. This div should have its display property set to 'print' for printing purposes, while its display value remains 'none' for screen display. Other elements on the page can have their display properties adjusted to show on screen but hide during printing. This method, however, requires meticulous management of all page elements' display properties.
An alternative approach is to create a new, isolated webpage containing solely the HTML content to be printed. This new page can be dynamically loaded into a hidden iframe when the user clicks the print button. Once the iframe has fully loaded, the browser's print function can be triggered, and the embedded HTML will be printed without any unwanted page elements. This method offers greater flexibility and dynamic control over the printing process.
Here's an example using the second approach:
<code class="javascript">// Create an invisible iframe to hold the print-only HTML const printFrame = document.createElement('iframe'); printFrame.style.display = 'none'; document.body.appendChild(printFrame); // Dynamically load the print-only HTML into the iframe printFrame.onload = function() { // Trigger the browser's print function once the print-only page is loaded window.print(); } printFrame.src = 'print-only.html';</code>
This solution allows you to print specific HTML content conveniently upon button click without modifying the main webpage's appearance or content. It ensures that only the intended HTML is printed, providing a more user-friendly printing experience.
The above is the detailed content of How to Print Specific HTML Content on Button Click Without Printing the Entire Page?. For more information, please follow other related articles on the PHP Chinese website!