【问题标题】:How to hide content but still make it printable?如何隐藏内容但仍使其可打印?
【发布时间】:2015-06-22 04:36:30
【问题描述】:

我有一个元素 (#print-content) 正在使用这个 jQuery 插件打印:

https://github.com/DoersGuild/jQuery.print

我不希望这个元素显示在实际页面中,但我希望它显示在打印版本中。

我可以使用什么 CSS 属性使其仍显示在打印版本中?也许是height:0position absolute 0?”

【问题讨论】:

  • 你在这个插件上使用了 append 吗?

标签: javascript jquery html css printing


【解决方案1】:

您可以只使用媒体查询。

#print-content {
    display: none; /*** Remove from the body ***/
}

@media print {
    #print-content {
        display: block; /*** Show just in print ***/
    }
}

【讨论】:

  • 简短而完美的答案。
【解决方案2】:

AFAIK,你不能使用特定的 CSS 属性来控制元素是否被打印,但你可以使用 CSS 媒体查询来代替:

@media screen {
    #print-content {
        display: none;
    }
}

这将阻止元素在页面显示在屏幕上时呈现,但在打印时,它将根据您的其余 CSS 规则正常处理。


如果你想要相反的效果(隐藏在打印中,但显示在屏幕上),你可以使用这个:

@media print {
    #print-content {
        display: none;
    }
}

有关 CSS @media 查询的更多信息,请参阅 this page


仅供参考,默认情况下使用display: none; 隐藏内容,然后使用display: block; 在媒体查询中显示它是不好的做法。这是基于元素的显示类型为block 的假设,但也可能是其他任何类型,例如inlineinline-block 等。它也使用了两条规则而不是一条规则。

【讨论】:

    【解决方案3】:

    一种可能性是使用 CSS 以不干扰布局的方式隐藏元素。

    CSS:

    #print-content {
        display: none;  //may need !important
    }
    

    该元素及其子元素不应显示,子元素仍应打印。更多关于显示属性:http://www.w3schools.com/cssref/pr_class_display.asp

    另一个解决方案(Andreas Grech 在下面的帖子中)是使用单独的样式表:

    <link rel="stylesheet" type="text/css" href="print.css" media="print" />
    

    How do I hide an element when printing a web page?

    在打印样式表中,@media print {} 将用于定义应打印的内容。

    【讨论】:

      【解决方案4】:

      尝试使用.clone().attr()window.open().outerHTML

      html

      <pre id="print-content"> (<span class="light">highlighted</span> portion) </pre>
      <div>abc 123</div>
      <button id="save">Print</button>
      

      css

      .light {
          color:#0af;
      }
      #print-content {
          display:none;
      }
      

      js

      $("#save").click(function () {
          var text = $("body").clone();
          text.find("#print-content").attr("style", "display:block");
          text.find("#save, script").remove();
          var styles = $("style")[0].outerHTML;
          var popup = window.open("", "popup");
          popup.document.body.innerHTML = text[0].outerHTML + styles;
          popup.focus();
          popup.print();
      });
      

      jsfiddle http://jsfiddle.net/qz2too0o/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-09
        • 2011-06-16
        • 2019-12-09
        • 1970-01-01
        • 2011-07-15
        • 2011-07-19
        • 2016-01-07
        • 1970-01-01
        相关资源
        最近更新 更多