我已插入一条规则(带有for),其中包含以下内容:
document.styleSheets[0].insertRule(`#li${i}:after {content: "${data[2][i]}"; }`, 0);
如何更新或删除它?
为什么? : 因为如果我第二次使用新数据运行for循环,它将不会更新悬停的内容 (我在这里需要它:https://vengeur69.github.io/public/Wikipedia_api/)
示例:
I get data with the term "yes"
I get data with the term "no" but the content didn't change
谢谢
答案 0 :(得分:1)
要删除只需使用deleteRule()传递插入规则的索引
var index = document.styleSheets[0].insertRule(`#li${i}:after {content: "${data[2][i]}"; }`, 0);
document.styleSheets[0].deleteRule(index);
为了更新规则,请在插入规则的索引处访问cssRules
列表,然后更改样式属性
document.styleSheets[0].cssRules[index].style.content = "";
请注意,如果正在访问的样式表在外部链接,您将无法访问该规则,因为cssRules
将为null。因此,您必须将其删除并插回以更改其样式。
演示
var stylesheet = document.styleSheets[0];
var ruleIndex = 0;
function redRule(){
stylesheet.cssRules[ruleIndex].style.color = "red";
}
function blueRule(){
stylesheet.cssRules[ruleIndex].style.color = "blue";
}
function replaceRule(){
stylesheet.deleteRule(ruleIndex);
ruleIndex = stylesheet.insertRule("body { color:yellow; }",0);
}
ruleIndex = stylesheet.insertRule("body { color:black; }",0);
document.addEventListener('click',function(e){
switch(e.target.id){
case 'red':
redRule();
break;
case 'blue':
blueRule();
break;
case 'replace':
replaceRule();
break;
}
});

<style></style>
Text<br>
<button id="red">Change rule to red</button><br>
<button id="blue">Change rule to blue</button><br>
<button id="replace">Replace rule</button><br>
&#13;