javascript - 如何在打印时隐藏打印按钮?

标签 javascript jquery html

我想在不打开新标签页的情况下点击按钮打印页面。

我有以下几行代码可以为我完成这项工作。

function PrintDiv() {    
    var contents = document.getElementById("wrapper").innerHTML;
    var frame1 = document.createElement('iframe');
    frame1.name = "frame1";
    frame1.style.position = "absolute";
    frame1.style.top = "-1000000px";
    document.body.appendChild(frame1);
    var frameDoc = frame1.contentWindow ? frame1.contentWindow : frame1.contentDocument.document ? frame1.contentDocument.document : frame1.contentDocument;
    frameDoc.document.open();
    frameDoc.document.write('<html><head><title>DIV Contents</title>');
    frameDoc.document.write('</head><body>');
    frameDoc.document.write(contents);
    frameDoc.document.write('</body></html>');
    frameDoc.document.close();
    setTimeout(function () {
        window.frames["frame1"].focus();
        window.frames["frame1"].print();
        document.body.removeChild(frame1);
    }, 500);

    return false;
}

我在带有 id wrapper 的 div 中有一个打印按钮

<div id="button-container">
    <a href="#" id="PrintDiv" class="btn btn-success btn-primary"><span class="glyphicon glyphicon-print" aria-hidden="true"></span>Print</a>
</div>

我的问题是我无法在打印时隐藏打印按钮。

我已尝试隐藏以下行,但它在我的情况下不起作用。

$('#PrintDiv').css('visibility', 'hidden');

最佳答案

您需要有一个基于打印的 CSS 样式规则 - 您还可以设置其他基于打印的规则 - 例如文档大小、背景颜色、图像规范等:

@media print {
   #button-container{
      display: none;
   }
}

关于javascript - 如何在打印时隐藏打印按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42221888/

相关文章:

javascript - jQuery:缩放时scrollLeft 不准确

javascript - ng-if 消除了 Material Design lite 涟漪效应

javascript - 使用 jquery 设置多个选项值的样式 : Code works for a few option values only

php - 如何使 html 页面在任何浏览器中只能在一定程度上缩放?

javascript - 从 ajax jquery 安全调用 PHP Web 服务函数,添加身份验证

javascript - ng-include 和 $templateCache

javascript - 等值线图返回未定义

javascript - 将行动态添加到具有动态接收列数的表中

jquery - 从 Calendario.js 中删除事件

javascript - jQuery onclick 不工作 iOS 10 <a> 标签