[英]how to show the contents of a div only in the print file?
watch my code below.在下面看我的代码。 I have a content in a DIV that can be printed when the "PRINT" button is clicked.我在 DIV 中有一个内容,可以在单击“打印”按钮时打印。 It's working fine, however I need this div (and its contents) to be hidden from the site page and only shown in the print file.它工作正常,但是我需要将此 div(及其内容)从站点页面中隐藏并仅显示在打印文件中。 Do you suggest anything to me?你有什么建议给我吗?
function printDiv(printThis) { var printContents = document.getElementById(printThis).innerHTML; var originalContents = document.body.innerHTML; document.body.innerHTML = printContents; window.print(); document.body.innerHTML = originalContents; }
<div id="printThis"> content </div> <input type="button" onclick="printDiv('printThis')" value="PRINT" />
You can use css @media print
您可以使用 css @media print
This will hide all body elements and show only the div #printThis
and all its children.这将隐藏所有正文元素并仅显示 div #printThis
及其所有子元素。
@media print {
body * {
visibility: hidden;
}
#printThis, #printThis * {
visibility: visible;
}
#printThis {
width : 100%;
height : auto;
position: absolute;
left: 0;
top: 0;
}
}
js (No need to modify/hide elements. CSS will handle it) js(无需修改/隐藏元素。CSS 会处理它)
function printDiv( printThis ) {
window.print();
}
HTML: HTML:
<div id="printThis">
content
</div>
<input type="button" onclick="printDiv('printThis')" value="PRINT" />
If you are using bootstrap you can just use a simple bootstrap class to hide or show a content in Print如果您使用的是引导程序,则可以使用简单的引导程序类来隐藏或显示 Print 中的内容
<div class="hidden-print">content for non print</div>
<div class="visible-print">content for print only</div>
its easy with bootstrap.使用引导程序很容易。 first hide the div with the bootstrap class hidden-md hidden-sm hidden-lg hidden-xs
them make it visible with the `visible-print class edit your html to首先使用 bootstrap 类hidden-md hidden-sm hidden-lg hidden-xs
隐藏 div 他们使用`visible-print 类使其可见,将您的 html 编辑为
<div id="printThis" class="visible-print"> content </div> <input type="button" onclick="printDiv('printThis')" value="PRINT" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.