簡體   English   中英

無法打印特定的 div

[英]Cannot print a specific div

我正在使用此代碼打印特定的 div

CSS

<style type="text/css" media="print">
    * {
        display:none;
    }
    #printportion {
        display:block;
    }
</style>

腳本

<script>
    var printCalender=function () {
        setTimeout(window.print, 1500);
    }
</script>

當我在谷歌瀏覽器中運行我的頁面時,打印預覽窗口是空白的並顯示“打印預覽失敗”

問題是,無論您的目標元素在 DOM 中的位置如何,您的*選擇器都將匹配它擁有的任何和所有父元素(包括<html><body> ),因此永遠不會顯示該元素。
請參閱以下示例:

 * { display: none; } #showme { display: block; }
 <div id="showme">This will never be shown</div>

正如 Nit 所說,問題在於您的*選擇器。 您可以像這樣使用一個帶有@media print選擇器:

@media print {
  body.print-element *:not(.print) {
    display: none;
  }
}

這里有一個工作示例,您可以在其中打印任何單擊的元素和/或整個普通 HTML 文檔:

 function print_this(elem) { document.body.classList.add('print-element') elem.classList.add('print') window.print() document.body.classList.remove('print-element') elem.classList.remove('print') } document.querySelectorAll('div').forEach(elem => elem.onclick = () => print_this(elem))
 div { display: inline-flex; width: 200px; height: 200px; justify-content: center; align-items: center; background-color: #e9a9c7; color: #39464e; cursor: pointer; } @media print { body.print-element *:not(.print) { display: none; } }
 <div>Print 1</div> <div>Print 2</div>

注意:如果您看不到顏色,請記住在打印選項中單擊背景圖形 (Chrome) 或類似內容。

暫無
暫無

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

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