通过jquery打印隐藏数据

时间:2015-02-18 15:19:12

标签: javascript jquery html css ajax

我有以下代码用于显示我想要隐藏详细代码,并且只应该在打印期间:

<div>
    <ul>
        <li>
            <span style="font-size: 1.25em;">
                <strong>#dateformat(startdate, "mm-dd-yyyy")# - #dateformat(enddate, "mm-dd-yyyy")#</strong>
            </span><br/><br/>
            #fullLeft(stripHTML(details),30)#
            </div>
            <div style="display:none;" class="completedata" align="left">
                #details#
            </div>
        <li>
    </ul>
</div>
$(window).load(function() {
    $('li').each(function () {
        $(this).css({
            "page-break-after": "always"
        });
        $(".completedata").css('display','block');
        window.print();
    });
});

它显示加载时带有隐藏显示数据的打印代码,但是当我取消打印命令时,它会将隐藏的div显示为block并显示在显示屏幕中。

1 个答案:

答案 0 :(得分:3)

正确的方法是使用@media print

.completedata { display: none; }    
@media print 
{
    .completedata { display: block !important; }
}

$("button").on("click", function() {
  window.print();
});
.completedata {
  color: #e74c3c;
}
.completedata {
  display: none;
}
@media print {
  .completedata {
    display: block !important;
  }
  button { display: none; }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Assumenda impedit sapiente atque quas aliquam a voluptate obcaecati saepe incidunt itaque eligendi sequi optio delectus similique laborum unde sint consectetur magnam?</p>

<p class="completedata">I appear only when printing the page!</p>

<button>Print me</button>