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

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

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


当前回答

@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);
});

其他回答

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

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

总的来说,这些答案我都不太喜欢。如果你有一个类(比如printableArea),并把它作为body的直接子类,那么你可以在你的print CSS中这样做:

body > *:not(.printableArea) {
    display: none;
}

//Not needed if already showing
body > .printableArea {
    display: block;
}

对于那些在其他地方寻找printableArea的人,你需要确保显示printableArea的父元素:

body > *:not(.parentDiv),
.parentDiv > *:not(.printableArea) {
    display: none;
}

//Not needed if already showing
body > .printableArea {
    display: block;
}

使用可见性可能会导致大量间距问题和空白页面。这是因为可见性保持了元素的空间,只是将其隐藏起来,而在显示时将其移除,并允许其他元素占用其空间。

这个解决方案有效的原因是您不需要抓取所有元素,只需要将body的直接子元素隐藏起来。下面的其他解决方案使用display css,隐藏所有元素,这将影响printableArea内容内的所有内容。

我不建议使用javascript,因为你需要有一个用户点击的打印按钮,而标准的浏览器打印按钮不会有同样的效果。如果你真的需要这样做,我会做的是存储主体的html,删除所有不需要的元素,打印,然后添加回html。如前所述,我将避免这种情况,如果你可以和使用CSS选项如上所述。

注意:你可以添加任何CSS到打印CSS使用内联样式:

<style type="text/css">
@media print {
   //styles here
}
</style>

或者像我通常使用的链接标签:

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

我来这个派对已经很晚了,但我想提出另一种方法。我写了一个叫做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来排列想要打印的内容?阅读这篇文章获取更多的建议。

桑德罗的方法很有效。

我对它进行了调整,以允许多个printMe链接,特别是在选项卡页面和扩展文本中使用。

function processPrint(printMe){<——在这里调用一个变量

var printReadyElem = document.getElementById(printMe);<——删除了printMe周围的引号以请求一个变量

< a href = " javascript:无效(processPrint (' divID '));>Print</a> <——将要打印的div ID传递到函数上,将printMe变量转换为div ID。需要单引号