2015-06-22 46 views

回答

1

AFAIK,你不能用一个具体的CSS属性来控制元素是否打印或没有,但你可以使用CSS媒体查询来代替:

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

这将防止从渲染时被显示在屏幕上的页面,但在打印时,它通常会根据您的CSS规则的其他处理它的元素。


如果希望相反的效果(隐藏在打印,但显示在s上creen),您可以使用此:

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

对CSS @media查询的详细信息,请参阅this page


仅供参考,这是不好的做法是使用display: none;到默认隐藏的内容,然后使用display: block;来显示它在媒体查询。这是基于元素的显示类型为block的假设,但它可能非常类似于其他任何内容,如inline,inline-block等。它也使用两个规则而不是一个。

2

您只能使用媒体查询。

#print-content { 
    display: none; /*** Remove from the body ***/ 
} 

@media print { 
    #print-content { 
     display: block; /*** Show just in print ***/ 
    } 
} 
+0

简短而完美的答案。 – Bugfixer

0

一种可能性是使用CSS来隐藏在不与布局干涉的方式的元素。

CSS:

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

的元素,它是儿童不宜显示,子元素还是应该打印。更多关于显示属性:http://www.w3schools.com/cssref/pr_class_display.asp

(在后下由Andreas格列奇)另一种解决方案是使用一个单独的样式表:

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

How do I hide an element when printing a web page?

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

0

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

相关问题