如何使用JavaScript在div上打印内容? [英] How to use JavaScript to print the contents on a div?
问题描述
我想使用print()函数来打印<div class="pagecontent"></div>
I would like to use the print() function to print the contents of a <div class="pagecontent"></div>
我知道您可以执行onClick="window.print()"
之类的操作,但这会打印整个窗口...我只希望打印.pagecontent
的内容.
I know you can do something like onClick="window.print()"
but this prints the entire window...I only want the contents of .pagecontent
to be printed.
使用JavaScript或jQuery进行此操作最简单的方法是什么?
What's the easiest way I can go about doing this using JavaScript or jQuery?
推荐答案
最简单的方法是定义适用于@media=print
的样式表.基本上它会像这样:
Easiest way is to define a stylesheet that applies for @media=print
. It would basically have something like:
* {
display: none; /* hide all elements when printing */
}
.pageContent {
display: block; /* make any class="pageContent" elements visible while printing */
}
当然,这将使pageContent元素可见,但是根据*
规则,其中的任何内容仍将不可见.您将不得不使用它并只列出应该隐藏的顶级元素.
Of course, this would make the pageContent elements visible, but anything inside them would still be invisible from the *
rule. You'll have to play with this and list only the top-level elements that should be hidden.
这篇关于如何使用JavaScript在div上打印内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!