简体   繁体   English

如何动态设置媒体打印样式但保持媒体屏幕不变?

[英]How to dynamically set a media print style but leave media screen untouched?

I have a report, with a details section below.我有一份报告,下面有详细信息部分。 On screen, there are instructions to view the details with a button below, which toggles the list's visibility (display:).在屏幕上,有使用下方按钮查看详细信息的说明,该按钮可切换列表的可见性(显示:)。

When the report is printed , I only want the instructions visible if the list is also visible.打印报告时,如果列表也可见,我只希望说明可见。 If the list is hidden, I want the instructions also hidden (as it's on paper, it's irrelevant and makes it look like something is missing).如果列表被隐藏,我希望说明也被隐藏(因为它在纸上,它是不相关的,并且看起来好像缺少某些东西)。

I can't see how to set the media-print style in function toggleListVisibility().我看不到如何在 function toggleListVisibility() 中设置媒体打印样式。 Something along the lines of clsInstructions.addClass(media-print-display-none) and clsInstructions.removeClass(media-print-display-none)?类似于 clsInstructions.addClass(media-print-display-none) 和 clsInstructions.removeClass(media-print-display-none) 的东西?

@media print {
    .noprint, .noprint * {display: none !important;}
}

<p>...Main report summary...</p>
<p class='clsInstructions'>See list below for details and suggested actions.</p>
<button type='button' class='noprint' onclick='toggleListVisibility()'>Show / hide list</button>
<div id='myList' style='display:none;'>...details content here...</div>

function toggleListVisibility(){
  $('#myList').toggle();
  if ($('#myList').is(":visible")) {
    //make the instructions visible to the printer...
  } else {
    //make the instructions display:none to the printer, but still visible on screen. how???...
  }
}

The simplest way would be:最简单的方法是:

  1. Add a common class name between all the elements.在所有元素之间添加一个通用的 class 名称。
  2. Toggle all of them when you wish to print.当您希望打印时,将它们全部切换。

 $(".noprint").toggle(false); //window.print();
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="noprint">A</div> <div>B</div> <div class="noprint">C</div>

The .noprint tells jQuery to select all elements that have that the class noprint . .noprint告诉 jQuery 到 select 所有具有 class noprint的元素。 While # is normally used to identify individual elements, . #通常用于标识单个元素,而. is used to select all element with the class name.用于 select 名称为 class 的所有元素。

So, you can hide the elements prior printing:因此,您可以在打印之前隐藏元素:

addEventListener('beforeprint', (event) => { 
  $(".noprint").toggle(false);
});

And, show them after printing:并且,在打印后显示它们:

addEventListener('afterprint', (event) => { 
  $(".noprint").toggle(true);
});

However, in theory, you should be able to do this with pure CSS:但是,理论上,您应该能够使用纯 CSS 做到这一点:

 body { text-align:center; } @media print {.noprint { visibility: hidden; } }
 <h1 class="noprint">DO NOT PRINT THIS</h1> <h1 class="noprint">PRINT THIS</h1>

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

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