【问题标题】:How do I show a section on print but hide it on screen?如何在打印上显示一个部分但在屏幕上隐藏它?
【发布时间】:2014-07-24 03:32:07
【问题描述】:

我想在屏幕上隐藏图像/徽标,但希望它在打印时显示。虽然我的努力没有奏效。我的代码有什么问题?

<style>
@media print {
   #othersections, #ebooknav {display: none;}
   #test {width: 100%; margin-top: 150px;}
   #printlogo {display: block; margin-top: 0px;}
             }
</style>
<script>
function myFunction() {
    window.print();
}
</script>
<div id="printlogo" style="display: none;"><img src="/images/logo.png" /></div>
<div id="test" style="margin-right:220px; float:left;">
Content to be printed
</div>
<div id="ebooknav">
<a href="" title="Print Page" onclick="myFunction()"><img src="/printbutton.png" /></a>
</div>

【问题讨论】:

  • 您的display: none 是一个内联样式属性,默认情况下它总是会覆盖您&lt;style&gt; 标记中的任何CSS。我认为你根本不应该在这里使用内联样式,除非你不能修改你的 HTML。
  • 我还有哪些其他选择才能达到预期的效果?
  • 我想我终于通过删除内联样式解决了这个问题。非常感谢!!!

标签: css printing stylesheet


【解决方案1】:

感谢 BoltClock 提供的线索。我意识到这是由于样式优先级的冲突。样式可以根据以下情况相互覆盖(来源:w3schools: cascading order of multiple styles):

  1. 内联样式(在 HTML 元素内)- 最高优先级
  2. 内部样式表(在头部)
  3. 外部样式表
  4. 浏览器默认 - 最低优先级

在上面的问题中,我把内联样式去掉了,放到了内部样式表中,或者我以后也可以直接放到外部样式表中:

<style>
@media screen {
   #printlogo {display: none;}
              }
@media print {
   #othersections, #ebooknav {display: none;}
   #test {width: 100%; margin-top: 150px;}
   #printlogo {display: block; margin-top: 0px;}
             }
</style>
<script>
function myFunction() {
    window.print();
}
</script>
<div id="printlogo"><img src="/images/logo.png" /></div>
<div id="test" style="margin-right:220px; float:left;">
Content to be printed
</div>
<div id="ebooknav">
<a href="" title="Print Page" onclick="myFunction()"><img src="/printbutton.png" /></a>
</div>

终于成功了!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多