【问题标题】:print html page inside form element在表单元素内打印html页面
【发布时间】:2016-08-12 12:11:53
【问题描述】:

网页有<form>,需要将其发送到打印机进行打印。键盘 Cmd+P 将打印整个页面,这不是我想要的。

我将事件连接到页脚上的按钮,但不确定如何仅将 form 内容发送到打印机。知道怎么做吗?

$('form').get(0).innerHTML

【问题讨论】:

标签: javascript


【解决方案1】:

这可以使用media queries 轻松完成。它可以在 IE9 及更高版本、Chrome、FF 等中运行。对于 IE8,您可以使用 polyfills。

现在您要做的就是在打印时隐藏元素。在你的 css 中写这样的东西

@media print {
    #element-to-hide {
        display: none;
    }
}

这将在打印时完全隐藏不需要的元素。

【讨论】:

  • 事件认为这可行,但它留下了空白空间,其中要隐藏的元素是预期使用一页的表单内容,它仍然在打印机中占用 2 页,好像它在它自己的页面中,它只会打印一页。
  • 您也可以重新调整可见元素的宽度、高度等。这样打印时就没有空白了
【解决方案2】:

您可以像块一样从页面中获取该元素并使用 Javascript 打印它

<div class="print" onclick="PrintElem('#idFromPage')">

以及打印你需要的块的Js代码:

    function PrintElem(elem) {
    Popup($("body").html(), elem);
}

function Popup(data, elem) {
    var mywindow = window.open('', 'Page to Print', 'height=600,width=800');
    mywindow.document.write('<html><head><title>Print Document</title>');
    mywindow.document.write('<style> body * { visibility: hidden;  } .mobile-view {displa:none;} body, html { background:#fff !important;}   #' + elem + ', #' + elem + ' * {visibility: visible; } </style>');
    mywindow.document.write('</head><body>');
    mywindow.document.write(data);
    mywindow.document.write('</body></html>');

    mywindow.document.close(); // necessary for IE >= 10
    mywindow.focus(); // necessary for IE >= 10

    $(mywindow).on('load', function () {
        mywindow.print();
    });

    return true;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-11
    • 2012-04-22
    • 1970-01-01
    • 2012-04-07
    相关资源
    最近更新 更多