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

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

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


当前回答

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

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

其他回答

使用特殊的样式表进行打印

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

然后添加一个类,即。"noprint"到每个你不想打印的内容的标签。

在CSS中使用

.noprint {
  display: none;
}

你可以用这个: 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'。这不是解。

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

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

另一种不影响当前页面的方法,它还在打印时持久化css。这里的选择器必须是特定的div选择器,我们需要打印的内容。

printWindow(selector, title) {
   var divContents = $(selector).html();
   var $cssLink = $('link');
   var printWindow = window.open('', '', 'height=' + window.outerHeight * 0.6 + ', width=' + window.outerWidth  * 0.6);
   printWindow.document.write('<html><head><h2><b><title>' + title + '</title></b></h2>');
   for(var i = 0; i<$cssLink.length; i++) {
    printWindow.document.write($cssLink[i].outerHTML);
   }
   printWindow.document.write('</head><body >');
   printWindow.document.write(divContents);
   printWindow.document.write('</body></html>');
   printWindow.document.close();
   printWindow.onload = function () {
            printWindow.focus();
            setTimeout( function () {
                printWindow.print();
                printWindow.close();
            }, 100);  
        }
}

这里提供了一些时间显示外部css被应用到它。

我找到了解决办法。

@media print {
    .print-area {
        background-color: white;
        height: 100%;
        width: auto;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        z-index:1500;
        visibility: visible;
    }
    @page{
        size: portrait;
        margin: 1cm;
    }
/*IF print-area parent element is position:absolute*/
    .ui-dialog,
    .ui-dialog .ui-dialog-content{
        position:unset !important;
        visibility: hidden;
    }
}