简体   繁体   English

如何将类添加到特定样式表?

[英]How to add a class to a specific stylesheet?

I want to use CSSStyleSheet.insertRule() to insert a new class inside a specific stylesheet. 我想使用CSSStyleSheet.insertRule()在特定样式表内插入新类。 That stylesheet has the id "customStylesheet" for example. 例如,该样式表的ID为“ customStylesheet”。

This page says "A specific style sheet can also be accessed from its owner object (Node or CSSImportRule), if any.". 该页面说:“如果有样式表,也可以从其所有者对象(Node或CSSImportRule)进行访问。” However I can't figure out how to access that specific stylesheet. 但是我不知道如何访问特定的样式表。

It is fairly straight forward. 这是相当简单的。

var sheet = document.getElementById('customStylesheet').sheet;

sheet.insertRule('.someclass {display: none;}'); // was missing a ' here

Here is a fiddle showing it working. 这是一个小玩意儿,显示它正在工作。 I have updated the fiddle to show it working on a style tag in the head also. 我已经更新了小提琴,以显示它还在头部的样式标签上工作。

This can be done with no jQuery. 这可以不用jQuery来完成。 Say that you wished to set everything with the class purpleText to color: purple . 假设您希望将类purpleText所有内容设置为color: purple First, you would get the stylesheet using document.styleSheets[_index_].ownerNode.sheet . 首先,您将使用document.styleSheets[_index_].ownerNode.sheet获得样式表。 Next, use the insertRule() method. 接下来,使用insertRule()方法。 The parameter is just a string holding the CSS code, as in ".purpleText{color: purple}" . 参数只是保存CSS代码的字符串,如".purpleText{color: purple}" So, for the first stylesheet, the whole command would be document.styleSheets[0].ownerNode.sheet.insertRule(".purpleText{color: purple}"); 因此,对于第一个样式表,整个命令将为document.styleSheets[0].ownerNode.sheet.insertRule(".purpleText{color: purple}");

要通过ID获取styleSheet,请使用以下代码:

document.getElementById('stylesheet').sheet;

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

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