[英]How to print an specific DIV with its CSS
我需要打印一個特定的 DIV,但我看到的所有其他帖子都不包含 DIV 中的樣式,有沒有辦法用 javascript 中的一個函數來做到這一點?
我已經看過這篇文章和其他帖子Print content of a DIV
您可以選擇所有其他元素並將它們從頁面中隱藏(使用:not()
CSS 偽類排除目標),然后調用window.print()
打印頁面:
btn.addEventListener('click', function(){ document.body.querySelectorAll(':not(.red)').forEach(e => e.style.display = "none"); window.print(); })
div{ height:100px; border:1px solid; } .red{ background-color:red; } .blue{ background-color:blue; }
<div class="red"> red </div> <div class="blue"> blue </div> <button id="btn">Print Red div</button>
如果你想創建一個接受一個元素作為參數的函數,你可以循環遍歷所有元素,並檢查當前被循環遍歷的項是否為參數。 如果不是,則隱藏該元素。
演示:
btn.addEventListener('click', function(){ printWithStyles(document.querySelector('.red')); }) function printWithStyles(e){ document.body.querySelectorAll("*").forEach(f => f === e ? '' : f.style.display="none"); window.print(); }
div{ height:100px; border:1px solid; } .red{ background-color:red; } .blue{ background-color:blue; }
<div class="red"> red </div> <div class="blue"> blue </div> <button id="btn">Print Red div</button>
不幸的是,上面的函數隱藏了元素的子元素,這可能會導致問題。 我們可以通過檢查循環通過的元素是否包含在參數中來解決這個問題:
btn.addEventListener('click', function(){ printWithStyles(document.querySelector('.red')); }) function printWithStyles(e){ document.body.querySelectorAll("*").forEach(f => e.contains(f) ? '' : f.style.display="none"); window.print(); }
div{ height:100px; border:1px solid; } .red{ background-color:red; } .blue{ background-color:blue; }
<div class="red"> <h1>red</1> </div> <div class="blue"> blue </div> <button id="btn">Print Red div</button>
要在打印后取消隱藏所有元素,一種懶惰的方法是:
document.body.querySelector("*").forEach(e => e.style.display="none");
這將在打印之前顯示隱藏的元素
這是一個簡單的方法來做到這一點!
$('a.printPage').click(function(){ $('#report-summary').show(); window.print(); return false; });
#report-summary { } @page { size: auto; margin: 25mm 25mm 25mm 25mm; } @media print { #search, .printPage { display: none !important; } }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" referrerpolicy="no-referrer"></script> <div id="report-summary"> Content here ... </div> <div class="printbtn"> <a class="printPage" href="#">Print Report</a> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.