首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Javascript打印显示隐藏元素

Javascript打印显示隐藏元素
EN

Stack Overflow用户
提问于 2014-12-12 16:57:14
回答 3查看 270关注 0票数 0

我正在尝试构建一个使用php和javascript的计费系统。为此,我需要在一个新的选项卡中打印一些内容。为此,我将使用以下代码。其中变量divElements包含需要打印的表的内部html。

代码语言:javascript
复制
var print_body =
                  '<!DOCTYPE html><head><meta charset="utf-8"><title></title><link rel="stylesheet" href="style.css" type="text/css"></link></head><body style="background:none"><table class="dop" id="table" border="1" style="border-collapse:collapse;border-style:solid">'+
                  divElements +'</table></body>';
                //Print  Page
                  newWin= window.open("");
                  newWin.document.write(print_body);
                  newWin.print();

使用dop类,我试图隐藏不需要的元素。在打印预览设计时,正确显示,但当打印出来时,隐藏的元素在纸上打印。我认为问题在于打印函数在加载样式之前正在运行。请帮我解决这个问题。

新宿

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-12-12 17:02:15

不确定这是否回答了您的问题,但您可以将样式表加载到打印视图中,并可能将display: none;设置为元素。

下面是我使用的一个函数:

代码语言:javascript
复制
function print() {
    var popup = window.open('', 'print', 'height=600,width=700,scrollbars=yes');
    popup.document.write('<html><head><title>TITLE</title>');
    var printStylePath = '/Content/print.css';
    popup.document.write('<link rel="stylesheet" href="' + printStylePath + '" type="text/css" />');
    popup.document.write('</head><body>');
    popup.document.write(printBody);
    popup.document.write('</body>');
    popup.document.write('</html>');
    popup.document.close();
    popup.focus();
    popup.print();
    popup.close();
    return true;
}
票数 0
EN

Stack Overflow用户

发布于 2014-12-12 17:13:10

试试看

打印前调用document.close

代码语言:javascript
复制
var print_body = '<!DOCTYPE html><head><meta charset="utf-8"><title></title><link rel="stylesheet" href="style.css" type="text/css"></link></head><body style="background:none"><table class="dop" id="table" border="1" style="border-collapse:collapse;border-style:solid">'+
                  divElements +'</table></body>';
                //Print  Page
                  newWin= window.open("");
                  newWin.document.write(print_body);
                  newwin.document.close();
                  newWin.print();
票数 0
EN

Stack Overflow用户

发布于 2014-12-12 17:25:37

在css中使用@media,如下所示:

代码语言:javascript
复制
@media screen {
    p {
        font-family: verdana,sans-serif;
        font-size: 14px;
    }
}

@media print {
    p {
        font-size: 20px;
        color: red;
    }
}

因此,要隐藏或不显示打印机的元素为打印机定义了@media print

有关@media签出此链接的更多资源

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27448433

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档