使用Javascript在不影响打印样式的情况下更改显示样式(CSS)

Use Javascript to Change Display Styles (CSS) Without Affecting Print Styles

本文关键字:样式 显示 CSS 情况下 Javascript 影响 打印 使用      更新时间:2023-09-26

我有一个web应用程序,它利用一个单独的打印样式表来控制页面从打印机出来时的外观。直到我最近对该网站进行了一些Javascript增强之前,它一直运行得很好。其中一个增强功能允许用户冻结页眉、导航以及表格标题。这背后的Javascript做了一些CSS技巧来冻结屏幕上的元素。不幸的是,将position: fixed应用于我的页眉(例如)会导致它打印在每一页上,这不是一个理想的效果。如何使用Javascript在不影响打印样式的情况下调整客户端上的元素样式?

@media print { #foo { color: blue; } }               /* Print definition */
@media screen { #foo { color: green; } }             /* Display definition */
document.getElementById('foo').style.color = 'red';  /* Overrides both! */

而不是用以下内容更改元素的属性:

document.getElementById('foo').style.color = 'red'; 

添加一个新的<style>元素,例如:

$('<style>@media screen { #foo { color: green; } }</style>').appendTo('head');

如果可能的话,最好将所有需要的更改连接到一个<style>元素中。

!important添加到打印规则中。

你可以试试这个@媒体打印{#foo{color:blue!important;}}

问题是javascript.style.something编辑元素的内联css,因此它将覆盖正常的css类/id规则。

或者你可以,和班级一起工作。document.getElementById('fo').className='redText';

并将.redText保存在常规css文件中(而不是打印文件),这比用填充打印css要好得多!重要规则。

没有好的解决方案!我最终做的是利用IE中的onbeforeprintonafterprint函数(我在这里的位置是,我们只有IE用户)来"解冻"answers"重新冻结"元素。。。

window.onbeforeprint = function() {
  document.getElementById('foo').style.position = 'static';
}
window.onload = window.onafterprint = function() {
  var el = document.getElementById('foo');
  // Get element position and size
  // Set left/top/width/height properties
  // Set position to fixed
  el.style.position = 'fixed';
}

正确的解决方案不是将样式戳到节点上,而是将特定于屏幕的样式调整与只影响屏幕呈现的css类联系起来:

@media screen { .freeze { position: fixed; } } /* Display-only definition */

+

document.getElementById('foo').className = "freeze";

另外,这也使得只需一行js就可以轻松地更改大量样式,这也使事情变得更快、更容易维护。