簡體   English   中英

使用CSS僅打印隱藏內容

[英]Using css to only print hidden content

我正在構建一個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("");
            }
        });
    });

});

您可以將可打印內容插入隱藏的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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM