代码之家  ›  专栏  ›  技术社区  ›  user3250818

打印div的内容,但其中的某些元素除外,不起作用

  •  0
  • user3250818  · 技术社区  · 7 年前

    我想打印一个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>
    

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

    2 回复  |  直到 7 年前
        1
  •  1
  •   brk    7 年前

    实际上,新创建的窗口使用 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>');
    
        2
  •  1
  •   Ivo Facundo    7 年前

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

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

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

    推荐文章