gpt4 book ai didi

javascript - 尝试创建仅显示 3 个 div 的打印页面

转载 作者:行者123 更新时间:2023-11-28 01:42:45 24 4
gpt4 key购买 nike

我正在尝试编写一个代码来隐藏页面中除三个 div 之外的所有元素。这样人们就会有一个打印机友好的版本。我用 jQuery 编写了它,但是(这对我们的 vendor 来说是政治问题)它不会工作。

代码如下:

<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,但 strip 化一切都不起作用。有什么想法吗?

我觉得我使用的 getElementsByTagName 不正确,但我不确定。

最佳答案

错误地使用了 getElementsByTagName(它返回一个 NodeList,它没有 style 属性), 但这只是防止你有一个不同的问题:如果你隐藏 body,你对任何 inside body 做什么都没有关系, 它不会显示。

使用 CSS 可以更好地处理这个问题,使用打印样式表:

@media print {
/* ...rules to show and hide things here...*/;
}

我可能会做的是使用一个类来隐藏您不想打印的任何内容。事实上,我已经知道使用两个类:printno-printprint 表示“我只想在打印时看到这个”,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 printingShows only when not printing

打印时,您会看到:

Shows both on-screen and when printingShows only when printing

请注意示例中的 strong 元素。它的可见性由它的容器决定。

关于javascript - 尝试创建仅显示 3 个 div 的打印页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24944276/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com