简体   繁体   English

如何在打印样式媒体时使用javascript更改样式中的css规则?

[英]how to change css rules in style using javascript when the style media is print?

How do you change the css rule of #div1 in the style type="text/css" media="print" using javascript? 如何使用javascript更改样式类型=“text / css”media =“print”中#div1的css规则? I want to change the display to none on the click event of a checkbox/button. 我想在复选框/按钮的单击事件上将显示更改为无。

<style type="text/css" media="screen">
 #div1{
 display:visible;
}
</style

<style type="text/css" media="print">
 #div1{
 display:visible;
}
</style

Thank You in advance 先感谢您

Create a new CSS class that is applied to whatever div you're trying to hide for a particular printing action, and add a rule to the print style sheet that hides it 创建一个新的CSS类,该类应用于您尝试为特定打印操作隐藏的任何div ,并将规则添加到隐藏它的打印样式表中

<style type="text/css" media="print">
.print-hidden {
    display:none;
}
</style>

Your trigger might look something like: 您的触发器可能类似于:

<script>
document.getElementById('div1_trigger').onclick = function() {
    document.getElementById('div1').className = 'print-hidden';
}
</script>

Assuming you have multiple sections, you would also have to handle removing the print-hidden class when another section is triggered. 假设您有多个部分,则还必须在触发另一个部分时处理删除print-hidden类。

Also, display: visible; 另外, display: visible; is not a valid CSS rule, you probably want display: block; 不是一个有效的CSS规则,你可能想要display: block;

I would probably use window.getComputesStyle method, it will give the actual style of the element: 我可能会使用window.getComputesStyle方法,它会给出元素的实际样式:

window.getComputedStyle(div1,null).getPropertyValue("display")

See docs for details: https://developer.mozilla.org/en/DOM:window.getComputedStyle 有关详细信息,请参阅文档: https//developer.mozilla.org/en/DOM : window.getComputedStyle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM