我有一个显示许多帖子的页面,并允许打印一个帖子(div
及其所有子项。)
单击打印按钮,我会浏览页面上的每个元素并按如下方式设置样式:
要打印的div设置为类printme
,它将top
和left
属性设置为0并将position
设置为absolute
打印的孩子的div是独自留下的
如果元素是要打印的div的父元素,我会添加设置print-visibility-hide
的类visibility: hidden
。
否则,我会添加一个设置display: none
的类。输出结果如下所示。
除了打印空白页外,一切正常 - 我认为是由于父div使用visibility: hidden
来隐藏内容,因此仍占用空间。
有没有办法打印我的div并以某种方式移除或折叠这个额外的空间?
HTML - 我最终得到了以下内容(删除了所有内容以简洁明了):
<body class="print-visibility-hide">
<div class="page-container print-visibility-hide">
<div class="main print-visibility-hide">
<div class="main-content d-section-top print-visibility-hide" id="main-content" style="background: transparent none repeat scroll 0% 0%; margin-left: 145px;">
<div id="gemwrapper" class="gemwrapper print-visibility-hide" style="display: block;">
<div class="gem-content-wrapper d-item d-section print-visibility-hide">
<div class="gem-content-main gems print-visibility-hide">
<div class="print-visibility-hide">
<div style="display: block;" id="s-g1353" class="print-visibility-hide">
<table class="print-visibility-hide">
<tbody class="print-visibility-hide">
<tr class="item tools print-visibility-hide">
<td class="textarea print-visibility-hide">
<div id="gparent1353" class="textarea print-visibility-hide">
<div id="gx1353" class="printme">
<pre>
This is the text I am printing which can be any length.</pre>
CSS
@media print {
body * {
visibility: hidden;
}
html,
body {
height: auto;
}
.print-display-none,
.print-display-none * {
display: none !important;
}
.print-visibility-hide,
.print-visibility-hide * {
visibility: hidden !important;
}
.printme,
.printme * {
visibility: visible !important;
}
.printme {
position: absolute;
left: 0;
top: 0;
}
.printme,
.printme:last-child {
page-break-after: avoid;
}
}
答案 0 :(得分:5)
使用@media打印像这样:
@media print {
html, body {
border: 1px solid white;
height: 99%;
page-break-after: avoid;
page-break-before: avoid;
}
}
更新2:
使用此代码:代替您的代码
@media print {
html, body {
border: 1px solid white;
height: 99%;
page-break-after: avoid !important;
page-break-before: avoid !important;
}
.print-display-none,
.print-display-none * {
display: none !important;
}
.print-visibility-hide,
.print-visibility-hide * {
visibility: hidden !important;
}
.printme,
.printme * {
visibility: visible !important;
}
.printme {
position: absolute;
left: 0;
top: 0;
}
}