如何打印指定的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来排列想要打印的内容?阅读这篇文章获取更多的建议。

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

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

print.css:

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

我有多个图像,每个图像都有一个按钮,需要单击一个按钮来打印每个带有图像的div。如果我在浏览器中禁用了缓存,并且图像大小在Chrome中没有改变,这个解决方案就可以工作:

        function printDiv(divName) {

        var printContents = document.getElementById(divName).innerHTML;
        w = window.open();

        w.document.write(printContents);
        w.document.write('<scr' + 'ipt type="text/javascript">' + 'window.onload = function() { window.print(); window.close(); };' + '</sc' + 'ript>');

        w.document.close(); // necessary for IE >= 10
        w.focus(); // necessary for IE >= 10

        return true;
    }

<div id="printableArea">
      <h1>Print me</h1>
</div>

<input type="button" onclick="printDiv('printableArea')" value="print a div!" />

在css3中,你可以使用以下功能:

body *:not(#printarea) {
    display: none;
}

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

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