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

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

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


当前回答

我来这个派对已经很晚了,但我想提出另一种方法。我写了一个叫做PrintElements的小JavaScript模块,用于动态打印网页的各个部分。

It works by iterating through selected node elements, and for each node, it traverses up the DOM tree until the BODY element. At each level, including the initial one (which is the to-be-printed node’s level), it attaches a marker class (pe-preserve-print) to the current node. Then attaches another marker class (pe-no-print) to all siblings of the current node, but only if there is no pe-preserve-print class on them. As a third act, it also attaches another class to preserved ancestor elements pe-preserve-ancestor.

一个非常简单的补充只打印的css将隐藏和显示各自的元素。这种方法的一些好处是保留了所有的样式,它不需要打开一个新窗口,不需要移动大量的DOM元素,而且通常它对原始文档是非侵入性的。

请参阅演示,或阅读相关文章以获得更多详细信息。

其他回答

我尝试了提供的许多解决方案。没有一个是完美的。它们要么丢失CSS,要么不能在所有浏览器中工作。我找到了一个完美而简单的解决方案,既不丢失CSS,也适用于所有浏览器。

Html

<div class="row" id="print-div">
      Your html 
    </div>

打印稿

let popupWin = window.open('', '_blank', 'width=1080,height=595');
let printContents = document.getElementById("print-div").innerHTML;
let printHead = document.head.innerHTML;
popupWin.document
    .write(`<html>
     ${printHead}
    <body onload="window.print();">${printContents}</body></html>`);
popupWin.document.close();

到目前为止,所有的答案都是有缺陷的——它们要么涉及在所有内容中添加class="noprint",要么会在#printable中混乱显示。

我认为最好的解决方案是在不可打印的东西周围创建一个包装器:

<head>
    <style type="text/css">

    #printable { display: none; }

    @media print
    {
        #non-printable { display: none; }
        #printable { display: block; }
    }
    </style>
</head>
<body>
    <div id="non-printable">
        Your normal page contents
    </div>

    <div id="printable">
        Printer version
    </div>
</body>

当然,这并不是完美的,因为它涉及到在HTML中移动一些东西……

我拿起使用JavaScript的内容,并创建了一个窗口,我可以打印代替…

@Kevin佛罗里达 如果你有同一个类的多个div,你可以这样使用它:

 <div style="display:none">
   <div id="modal-2" class="printableArea">
     <input type="button" class="printdiv-btn" value="print a div!" />
   </div>
 </div>

我使用的是Colorbox内内容类型

$(document).on('click', '.printdiv-btn', function(e) {
    e.preventDefault();

    var $this = $(this);
    var originalContent = $('body').html();
    var printArea = $this.parents('.printableArea').html();

    $('body').html(printArea);
    window.print();
    $('body').html(originalContent);
});

你可以用这个: http://vikku.info/codesnippets/javascript/print-div-content-print-only-the-content-of-an-html-element-and-not-the-whole-document/

或者使用visibility:visible和visibility:hidden css属性和@media print{}

'display:none'将隐藏所有嵌套的'display:block'。这不是解。