【问题标题】:How to hide content but still make it printable?如何隐藏内容但仍使其可打印?
【发布时间】:2015-06-22 04:36:30
【问题描述】:
【问题讨论】:
标签:
javascript
jquery
html
css
printing
【解决方案1】:
您可以只使用媒体查询。
#print-content {
display: none; /*** Remove from the body ***/
}
@media print {
#print-content {
display: block; /*** Show just in print ***/
}
}
【解决方案2】:
AFAIK,你不能使用特定的 CSS 属性来控制元素是否被打印,但你可以使用 CSS 媒体查询来代替:
@media screen {
#print-content {
display: none;
}
}
这将阻止元素在页面显示在屏幕上时呈现,但在打印时,它将根据您的其余 CSS 规则正常处理。
如果你想要相反的效果(隐藏在打印中,但显示在屏幕上),你可以使用这个:
@media print {
#print-content {
display: none;
}
}
有关 CSS @media 查询的更多信息,请参阅 this page。
仅供参考,默认情况下使用display: none; 隐藏内容,然后使用display: block; 在媒体查询中显示它是不好的做法。这是基于元素的显示类型为block 的假设,但也可能是其他任何类型,例如inline、inline-block 等。它也使用了两条规则而不是一条规则。
【解决方案4】:
尝试使用.clone()、.attr()、window.open()、.outerHTML
html
<pre id="print-content"> (<span class="light">highlighted</span> portion) </pre>
<div>abc 123</div>
<button id="save">Print</button>
css
.light {
color:#0af;
}
#print-content {
display:none;
}
js
$("#save").click(function () {
var text = $("body").clone();
text.find("#print-content").attr("style", "display:block");
text.find("#save, script").remove();
var styles = $("style")[0].outerHTML;
var popup = window.open("", "popup");
popup.document.body.innerHTML = text[0].outerHTML + styles;
popup.focus();
popup.print();
});
jsfiddle http://jsfiddle.net/qz2too0o/