简体   繁体   English

无法打印特定的 div

[英]Cannot print a specific div

I am using this code to print a specific div我正在使用此代码打印特定的 div

CSS CSS

<style type="text/css" media="print">
    * {
        display:none;
    }
    #printportion {
        display:block;
    }
</style>

Script脚本

<script>
    var printCalender=function () {
        setTimeout(window.print, 1500);
    }
</script>

When I run my page in google chrome, the print preview window is blank and shows 'print preview failed'当我在谷歌浏览器中运行我的页面时,打印预览窗口是空白的并显示“打印预览失败”

The issue is that regardless of where your targeted element is positioned in the DOM, your * selector will match any and all parents it has (including <html> and <body> ) so the element will never be shown.问题是,无论您的目标元素在 DOM 中的位置如何,您的*选择器都将匹配它拥有的任何和所有父元素(包括<html><body> ),因此永远不会显示该元素。
See the below example:请参阅以下示例:

 * { display: none; } #showme { display: block; }
 <div id="showme">This will never be shown</div>

As Nit said the problem is with your * selector.正如 Nit 所说,问题在于您的*选择器。 You can use one selector with @media print like this:您可以像这样使用一个带有@media print选择器:

@media print {
  body.print-element *:not(.print) {
    display: none;
  }
}

Here you have a working example where you can print any clicked element and/or the entire normal HTML document:这里有一个工作示例,您可以在其中打印任何单击的元素和/或整个普通 HTML 文档:

 function print_this(elem) { document.body.classList.add('print-element') elem.classList.add('print') window.print() document.body.classList.remove('print-element') elem.classList.remove('print') } document.querySelectorAll('div').forEach(elem => elem.onclick = () => print_this(elem))
 div { display: inline-flex; width: 200px; height: 200px; justify-content: center; align-items: center; background-color: #e9a9c7; color: #39464e; cursor: pointer; } @media print { body.print-element *:not(.print) { display: none; } }
 <div>Print 1</div> <div>Print 2</div>

Note : if you cannot see colors remember to click Background Graphic (Chrome) or similar in your print options.注意:如果您看不到颜色,请记住在打印选项中单击背景图形 (Chrome) 或类似内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM