【问题标题】:Using css to only print hidden content使用 css 只打印隐藏内容
【发布时间】:2017-04-11 18:08:40
【问题描述】:

我正在构建一个需要在用户单击按钮时打印报告的 Web 应用程序。报告中的任何内容在页面上都不可见,只有在用户单击按钮时才会创建。我最初的想法是简单地打开一个新窗口,设置内容,然后在打印后关闭窗口。但是,这不是一个选项,因为用户正在使用无法打开新选项卡/窗口的信息亭模式的浏览器。要求是报表需要在不从当前页面重定向的情况下打印。只打印报表本身,不能包含当前页面的任何内容。

我知道这已经在这里发布了多次,但我查看了很多这样的帖子,这就是我现在的情况。

当我单击按钮并打印页面时,它会打印一个空白页。我不知道为什么这不起作用。

这是我目前所拥有的

HTML

<html class="printable">
<head>
    <link rel="stylesheet" type="text/css" href="css/print-style.css">
    <script src="js/jquery.js"></script>
    <script src="js/report.js"></script>
</head>
<body class="printable">
    <div>
        <h1>Content that shouldn't print</h1>
        <h2>Content that shouldn't print</h2>
        <h3>Content that shouldn't print</h3>
        <h4>Content that shouldn't print</h4>
    </div>
    <div id="report" class="print-only"></div>
</body>
</html>

CSS

@media print {
    :not(.printable) {
        display: none;
    }

    .print-only {
        display: block;
    }
}

.print-only {
    display: none;
}

JavaScript

$(function() {
    $("#print-button").click(function() {
        $.ajax({
            url: "get-report",
            success: function(resp) {
                $("#report").html(resp); // populate the report div with the response from the ajax call
                $("#report").children("*").addClass("printable"); // make all children of the report div printable
                window.print();
                $("#report").html("");
            }
        });
    });

});

【问题讨论】:

    标签: javascript html css printing


    【解决方案1】:

    您可以将可打印的内容插入到隐藏的 div 中,并使用 @media 打印来取消隐藏。

    .print {display:none;}
    
    @media print {
      body :not(.both) {display:none;}
      .print  {display:block!important;}
    }
    <html>
    <head></head>
    <body>
      <div>
        Screen content
      </div>
      
      <div class="both">Both media</div>
      
      <div class="print">
        Printable content
      </div>  
    </body>
    </html>

    【讨论】:

    • 这就是我想做的事情
    • 您插入打印块的所有内容都将在可打印版本中,仅此而已。我添加了一个示例代码,答案是你要找的还是我遗漏了什么?
    • 您的代码和我的代码之间的唯一区别是,我将打印时要隐藏的内容列入黑名单,而您将其列入白名单。这个解决方案对我不起作用。
    • 好吧,我想我不应该说唯一的区别。我的解决方案尝试允许打印 print-only 隐藏内容和标记为 printable 的内容
    • 如果是这个问题,只需使用上面更新的代码,您只需添加printableboth 类。
    猜你喜欢
    • 2011-06-16
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多