簡體   English   中英

如何動態設置媒體打印樣式但保持媒體屏幕不變?

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

我有一份報告,下面有詳細信息部分。 在屏幕上,有使用下方按鈕查看詳細信息的說明,該按鈕可切換列表的可見性(顯示:)。

打印報告時,如果列表也可見,我只希望說明可見。 如果列表被隱藏,我希望說明也被隱藏(因為它在紙上,它是不相關的,並且看起來好像缺少某些東西)。

我看不到如何在 function toggleListVisibility() 中設置媒體打印樣式。 類似於 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???...
  }
}

最簡單的方法是:

  1. 在所有元素之間添加一個通用的 class 名稱。
  2. 當您希望打印時,將它們全部切換。

 $(".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>

.noprint告訴 jQuery 到 select 所有具有 class noprint的元素。 #通常用於標識單個元素,而. 用於 select 名稱為 class 的所有元素。

因此,您可以在打印之前隱藏元素:

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

並且,在打印后顯示它們:

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

但是,理論上,您應該能夠使用純 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