我正在尝试编写一个隐藏三个div之外的页面所有元素的代码。因此人们将拥有适合打印机的版本。我在jQuery中写了它,但(它与我们的供应商是政治的)它不起作用。
以下是代码:
<script type='text/javascript'>function prntz(){
document.getElementsByTagName("body").style.display = "none";
document.getElementById("hider").style.display = "inline";
document.getElementById("hider1").style.display = "inline";
document.getElementById("hider2").style.display = "inline";
};</script>
单击按钮时调用prntz函数的位置。我已经能够显示div了,但是一切都没有用。任何想法?
我觉得我错误地使用了getElementsByTagName,但我不确定。
答案 0 :(得分:1)
错误地使用getElementsByTagName
(它返回NodeList
,但没有style
属性),但这只是阻止了不同的问题:如果你隐藏body
,那么你对 body
内的任何内容做什么都没关系,它就不会显示。
使用打印样式表可以更好地处理CSS:
@media print {
/* ...rules to show and hide things here...*/;
}
我可能会做的是使用一个类来隐藏任何你不想要打印的东西。事实上,我已经知道使用两个类:print
和no-print
。 print
表示“我只想在打印时看到此内容”,no-print
表示“我只想在不打印时看到此内容”。任何没有一个类或另一个类的东西都会在屏幕上和打印时显示。您只能将其用于相关事物的顶层。
规则如下:
@media not print {
.print {
display: none;
}
}
@media print {
.no-print {
display: none;
}
}
示例:Live Copy
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
<style>
@media not print {
.print {
display: none;
}
}
@media print {
.no-print {
display: none;
}
}
</style>
</head>
<body>
<p>Shows both on-screen and when printing</p>
<p class="print">Shows only when printing</p>
<p class="no-print">Shows only when <strong>not</strong> printing</p>
</body>
</html>
在屏幕上,您会看到:
Shows both on-screen and when printing Shows only when not printing
打印时,您会看到:
Shows both on-screen and when printing Shows only when printing
请注意示例中的strong
元素。它的能见度由容器决定。
答案 1 :(得分:0)
隐藏元素中的所有元素都将被隐藏,因此通过在主体上设置display: none
,身体内的所有div也将被隐藏。
另一种方法是使用打印类型表,例如:
/* hide all divs */
div { display: none; }
/* show the hider divs, and the divs inside them */
#hider, #hider2, #hider3,
#hider div, #hider2 div, #hider3 div { display: block; }