[英]Use Javascript to Change Display Styles (CSS) Without Affecting Print Styles
我有一个 web 应用程序,它使用单独的打印样式表来控制页面从打印机出来时的外观。 在我最近对该站点进行了一些 Javascript 增强之前,这一直运行良好。 其中一项增强功能允许用户冻结页面 header 和导航以及表格标题。 这背后的 Javascript 做了一些 CSS 诡计来冻结屏幕上的元素。 不幸的是,应用position: fixed
to my header (例如)会导致它在每一页上打印,这不是预期的效果。 如何在客户端使用 Javascript 调整元素 styles 而不影响打印样式?
@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';
append 一个新的<style>
元素,例如:
$('<style>@media screen { #foo { color: green; } }</style>').appendTo('head');
如果可能的话,最好将所有需要的更改连接到一个<style>
元素中。
将!important
添加到您的打印规则中。
你可以试试这个@media print { #foo { color: blue;important; } }
问题是 javascript.style.something,编辑元素的内联 css,因此它将覆盖正常的 css 类/ID规则。
或者,您可以使用课程。 document.getElementById('foo').className = 'redText';
并将 .redText 保存在您的常规 css 文件(不是打印文件)中,这比使用 .important 规则填充您的打印 css 要好得多。
没有好的解决办法! 我最终做的是利用 IE 中的onbeforeprint
和onafterprint
功能(我在 position 中,我们只有 IE 用户)来“解冻”和“重新冻结”元素......
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';
}
正确的解决方案不是将 styles 戳到节点上,而是将您的屏幕特定样式调整绑定到 css 类,这些类只会影响您的屏幕再现:
@media screen {.freeze { position: fixed; } } /* Display-only definition */
+
document.getElementById('foo').className = "freeze";
作为奖励,这也使得只需一行 js 即可轻松更改大量 styles,这也使事情变得更快、更容易维护。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.