[英]Programatically create new CSS rules in a stylesheet
For creating new CSS rules in a stylesheet, as of now, I only know .insertRule()
(excluding the non-standard ways). 到目前为止,为了在样式表中创建新的CSS规则,我只知道
.insertRule()
(不包括非标准方式)。
Are there any other ways of creating more CSS rules? 还有其他创建更多CSS规则的方法吗? Something, for example:
某事,例如:
Warning: this is not standard, it is just an example to display the intent 警告:这不是标准,这只是显示意图的一个示例
var rule = new CSSStyleRule();
rule.selectorText = '.selector';
rule.style.display = 'block';
rule.style.color = 'red';
ruleSet.append(rule);
Anything like or somewhat like the above works as an answer. 任何与上述类似或类似的内容都可以作为答案。 Instead of
new
, it may be document.createCssRule()
or stylesheet.createCssRule()
... I just this it would be useful for a piece of software I'm developing which left me if there's a programatically way of modifying values in such interface where to add new stuff is not restricted to a parsed string. 代替
new
可能是document.createCssRule()
或stylesheet.createCssRule()
...我只是想这对我正在开发的软件很有用,如果可以通过编程方式修改这样的值在其中添加新内容的接口不限于已解析的字符串。
Do not worry about IE9 and below when answering, please. 回答时,请不要担心IE9及以下版本。
Note: (to unclose) This is not about how to find and modify current CSS rules, this is about making new ones without using the text parser which is what .insertRule()
is without building a complete CSS string like .insertRule()
requires. 注意:(不公开)这不是关于如何查找和修改当前CSS规则,而是关于在不使用文本解析器的情况下创建新规则,而
.insertRule()
则是在不构建.insertRule()
这样的完整CSS字符串的情况下进行的。
You could append a new style
element to your head
and just append rules to it: 您可以在
head
添加一个新的style
元素,然后在其上添加规则:
function addStyle(newRules){
if(document.getElementById("jsAddedRules")){
document.getElementById("jsAddedRules").innerHTML+=newRules;
}else{
var style=document.createElement("style");
style.setAttribure("id","jsAddedRules");
style.innerHTML=newRules;
document.getElementsByTagName("head")[0].appendChild(style);
}
}
And then just call your function when you want to add rules: 然后在要添加规则时调用函数:
addStyle(
".selector{\
display:block;\
color:red;\
}"
);
You can add an empty rule, get it, and modify it: 您可以添加一个空规则,获取它,然后对其进行修改:
function appendRule(sheet) { var len = sheet.cssRules.length; sheet.insertRule('*{}', len); return sheet.cssRules[len]; } var rule = appendRule(document.styleSheets[0]); rule.selectorText = '.selector'; rule.style.display = 'block'; rule.style.color = 'red';
<span class="selector">I should become red.</span> <span>I should be at the next line and not become red.</span>
However, modifying selectorText
does not seem to work on Firefox. 但是,修改
selectorText
似乎在Firefox上不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.