【发布时间】:2020-05-01 15:21:36
【问题描述】:
感谢您帮助我!我正在尝试使用 CSS Media 查询打印特定的 div。在点击打印时,根据他们点击的 div,我想隐藏所有其他元素,除了他们点击的 body div。
一切都很好,除了当我去打印时,元素在它们原来的位置,我假设是因为“隐藏”属性......其他 div 实际上并没有消失。我不能使用 display:none 属性,因为它会弄乱动态生成的元素。
任何关于如何让所选元素打印在首页的前面和中心的建议都会有所帮助!
这是我用于打印的 CSS
<style>
/*CSS FOR HIDING ALL ELEMENTS EXCEPT THE PRINTED ONE*/
@media print {
/*set all HTML elements to hidden*/
body * {
visibility: hidden;
}
/*CSS classes to set chosen elements and all their children to visible*/
.section-to-print-head, .section-to-print-body, .section-to-print-head *, .section-to-print-body * {
visibility: visible;
display: block;
}
/*POSITIONING OF HEAD*/
.section-to-print-head {
position: absolute;
left: 0;
top: 0;
width: 100%;
page-break-after: avoid;
display: block;
}
/*POSITIONING OF BODY*/
.section-to-print-body {
position: absolute;
left: 5;
top: 0;
width: 100%;
z-index: 100;
}
.section-to-print-body:last-child {
page-break-after: avoid;
}
}
</style>
这是带有按钮和点击功能的 HTML
<div class="row infoAreaToPrint">
<div class="col-lg-5">
<div class="card">
<div class="card-body">
<p class="h4 border-bottom mb-0">
Customer: <?php echo $custName ?></p>
<span>
<button
onclick="printThisTableDiv('.infoAreaToPrint')">Print Info
</button>
</span>
这是我调用的函数,用于隐藏除我要打印的元素之外的所有元素
function printThisTableDiv(tableID) {
let existingTags = document.querySelectorAll('.section-to-print-body');
let i;
for (i = 0; i < existingTags.length; i++) {
existingTags[i].classList.remove('section-to-print-body');
}
document.querySelector(tableID).classList.add("section-to-print-body");
window.print();
};
【问题讨论】:
标签: javascript html css printing media-queries