除了一些元素之外,打印div的内容,不起作用

时间:2018-01-05 17:18:07

标签: javascript hide print-preview

我想打印一个div的内容,并且不想在打印预览中显示这个div中的一些元素,我试图给@media print中的那些元素提供noprint类,但没有成功!请帮忙! 这是Javascript

<script type="text/javascript">
    function PrintPanel() {
        var panel = document.getElementById("content");
        var printWindow = window.open('', '', 'height=400,width=800');
        printWindow.document.write('<html><head><title>DIV Contents</title>');
        printWindow.document.write('</head><body >');
        printWindow.document.write(panel.innerHTML);
        printWindow.document.write('</body></html>');
        printWindow.document.close();
        setTimeout(function () {
            printWindow.print();
        }, 500);
        return false;
    }

</script>

这是css

<style>
    .noprint {
        color: red;
    }

    @media print {
        p {
            color: green;
        }

        .noprint {
            display: none;
        }
    }
</style>

这是html

<body>
<div id="content">
    <p>show this, in print preview</p>

    <div class="noprint">
        dont show this, in print preview!
    </div>
</div>
<a id="btnPrint" runat="server" Text="Print" onclick="PrintPanel();" style="cursor:pointer;">print</a>

我在jsfiddle中提供了一个示例: sample link

2 个答案:

答案 0 :(得分:1)

我添加此代码以在弹出窗口中删除元素之前非常简单! 此代码仅通过Jquery的$()等查询获取元素,并使用removeChild(element)方法从父节点 panel 中删除,在本例中为div。

var el = document.querySelector('.noprint');
panel.removeChild(el);

https://jsfiddle.net/457vjehs/6/

答案 1 :(得分:1)

实际上,使用window.open创建的新窗口没有附加任何样式。

这是一张快照

Snapshot of the newly created window

可以通过在以下代码中添加内联样式来添加样式

printWindow.document.write('<html><head><style media="print">' +
            'p {color: green;}.noprint {display: none !important;}</style><title>DIV Contents</title>');