【问题标题】:How do I print DIV content of HTML to printer with Javascript only? [duplicate]如何仅使用 Javascript 将 HTML 的 DIV 内容打印到打印机? [复制]
【发布时间】:2019-06-21 12:56:35
【问题描述】:

我需要打印 HTML div 的内容。为此,我添加了一个按钮。我正在尝试调用一个函数 onclick of button 以使用 Javascript 打印 div 内容。

【问题讨论】:

  • 欢迎来到 StackOverflow。请参考this

标签: javascript html css frontend


【解决方案1】:

以下是单击按钮时打印 div 的示例代码。

<body>
<div id='printarea'>
    <p>This is a sample text</p>
</div>
<button onclick="print()">Print</button>
</body>

<script>
function print() {
    var divToPrint = document.getElementById('printarea');
    var htmlToPrint = '' +
        '<style type="text/css">' +
        'table th, table td {' +
        'border:1px solid #000;' +
        'padding;0.5em;' +
        '}' +
        '</style>';
    htmlToPrint += divToPrint.outerHTML;
    newWin = window.open("");
    newWin.document.write("<h3 align='center'>Print Page</h3>");
    newWin.document.write(htmlToPrint);
    newWin.print();
    newWin.close();
}
</script>

【讨论】:

    【解决方案2】:

    您可以在 div 中添加一个 id 并使用:printWindow.document.write(document.getElementById("yourId").innerHtml)

    【讨论】:

    • 这将打印所有 div 元素,OP 想要的是打印 div 的内容,即 innerHtml 或更像 div 的 innerText。所以这在这里行不通。
    • 这将起作用:printWindow.document.write(document.getElementsByTagName("div")[0].innerHtml)
    • 我们不确定OP是否需要第一个div的内容。与他确认并更新您的答案:)
    • 他可以给div加一个id,使用:printWindow.document.write(document.getElementById("yourId").innerHtml)
    • 这是可能的。相应地更新您的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-25
    • 2011-11-10
    相关资源
    最近更新 更多