如何打印指定的div(无需手动禁用页面上的所有其他内容)?

我想要避免一个新的预览对话框,所以用这个内容创建一个新窗口是没有用的。

该页面包含了几个表格,其中一个包含了我想打印的div -表格是用web的视觉样式设计的,不应该显示在打印中。


当前回答

这里有一个通用的解决方案,只使用CSS,我已经验证工作。

@media print {
  body * {
    visibility: hidden;
  }
  #section-to-print, #section-to-print * {
    visibility: visible;
  }
  #section-to-print {
    position: absolute;
    left: 0;
    top: 0;
  }
}

其他方法都不太好。使用display很棘手,因为如果任何元素都没有display:none,那么它的后代也不会显示。要使用它,您必须更改页面的结构。

使用可见性效果更好,因为您可以为后代打开可见性。但是,不可见的元素仍然会影响布局,所以我将section-to-print移到左上角,以便正确打印。

其他回答

你可以使用一个单独的CSS样式来禁用除id为“printarea”的所有其他内容。

参见CSS设计:准备打印以获得更多的解释和示例。

使用jQuery,它就像这样简单:

w=window.open();
w.document.write($('.report_left_inner').html());
w.print();
w.close();

基于@Kevin Florida的回答,我做了一种方法来避免当前页面上的脚本因为覆盖内容而禁用。我使用其他文件称为“printScreen.php”(或。html)。把你想打印的所有东西都包装在一个div“printSource”中。用javascript,打开一个你之前创建的新窗口(“printScreen.php”),然后在顶部窗口的“printSource”中抓取内容。

这是代码。

主窗口:

echo "<div id='printSource'>";
//everything you want to print here
echo "</div>";

//add button or link to print
echo "<button id='btnPrint'>Print</button>";

<script>
  $("#btnPrint").click(function(){
    printDiv("printSource");
  });

  function printDiv(divName) {
   var printContents = document.getElementById(divName).innerHTML;
   var originalContents = document.body.innerHTML;
   w=window.open("printScreen.php", "_blank", "toolbar=yes,scrollbars=yes,resizable=yes,top=50,left=50,width=900,height=400");
   }
</script>

这是“printScreen.php”-另一个文件抓取内容打印

<head>
// write everything about style/script here (.css, .js)

</head>
<body id='mainBody'></body>
</html>


<script>
    //get everything you want to print from top window
    src = window.opener.document.getElementById("printSource").innerHTML;

    //paste to "mainBody"
    $("#mainBody").html(src);
    window.print();
    window.close();
</script>

如果你只想打印这个div,你必须使用指令:

@media print{
    *{display:none;}
    #mydiv{display:block;}
}

嗯……使用样式表的类型进行打印…例如:

<link rel="stylesheet" type="text/css" href="print.css" media="print" />

print.css:

div { display: none; }
#yourdiv { display: block; }