如何隐藏内容但仍使其可打印

How to hide content but still make it printable?

本文关键字:打印 何隐藏 隐藏      更新时间:2023-09-26

我有一个元素(#print-content)我正在用这个jQuery插件打印:

https://github.com/DoersGuild/jQuery.print

我不希望此元素显示在实际页面中,但我希望它显示在打印版本中。

我可以使用什么 CSS 属性,使其仍显示在打印版本中?也许height:0position absolute 0

只能使用媒体查询。

#print-content {
    display: none; /*** Remove from the body ***/
}
@media print {
    #print-content {
        display: block; /*** Show just in print ***/
    }
}

AFAIK,您不能使用特定的 CSS 属性来控制是否打印元素,但您可以使用 CSS 媒体查询:

@media screen {
    #print-content {
        display: none;
    }
}

这将防止元素在屏幕上显示页面时呈现,但在打印时,它将根据其余的 CSS 规则正常处理它。


如果你想要相反的效果(隐藏在打印中,但在屏幕上显示),你可以使用这个:

@media print {
    #print-content {
        display: none;
    }
}

有关 CSS @media查询的更多信息,请参阅此页面。


仅供参考,默认情况下使用 display: none; 隐藏内容,然后使用 display: block; 在媒体查询中显示内容是一种不好的做法。这是基于元素的显示类型是block的假设,但它可能是其他任何东西,如inlineinline-block等。它还使用两个规则而不是一个规则。

一种可能性是使用 CSS 以不干扰布局的方式隐藏元素。

.CSS:

#print-content {
    display: none;  //may need !important
}
元素

及其子元素不应显示,子元素仍应打印。有关显示属性的更多信息:http://www.w3schools.com/cssref/pr_class_display.asp

另一个解决方案(由Andreas Grech在下面的帖子中提出)是使用单独的样式表:

<link rel="stylesheet" type="text/css" href="print.css" media="print" />

打印网页时如何隐藏元素?

在打印样式表中,@media打印 {} 将用于定义应打印的内容。

尝试利用.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/