[英]How to add a class to a specific stylesheet?
我想使用CSSStyleSheet.insertRule()在特定样式表内插入新类。 例如,该样式表的ID为“ customStylesheet”。
该页面说:“如果有样式表,也可以从其所有者对象(Node或CSSImportRule)进行访问。” 但是我不知道如何访问特定的样式表。
这是相当简单的。
var sheet = document.getElementById('customStylesheet').sheet;
sheet.insertRule('.someclass {display: none;}'); // was missing a ' here
这是一个小玩意儿,显示它正在工作。 我已经更新了小提琴,以显示它还在头部的样式标签上工作。
这可以不用jQuery来完成。 假设您希望将类purpleText
所有内容设置为color: purple
。 首先,您将使用document.styleSheets[_index_].ownerNode.sheet
获得样式表。 接下来,使用insertRule()
方法。 参数只是保存CSS代码的字符串,如".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.