我用一个简单的例子来解释这个问题。 我有以下 html 页面。很简单。
有一个名为 TestDiv 的 CSS 类和两个 javascript 函数。
- addDiv 创建新的 div 并通过单击按钮“添加新的 div” 将其附加到页面。
- setBlue 是我想更改具有 TestDiv 类的 div 颜色的函数,我不知道如何。
您可以看到我在 setBlue 函数中编写了一些代码来更改当前生成的 Div。但我不知道如何更改类以影响之后由 addDiv 函数生成的新 div。
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
.TestDiv {
color:red;
}
</style>
<script>
function addDiv() {
var newDiv = document.createElement("div")
newDiv.className = "TestDiv";
newDiv.innerHTML = "test";
document.getElementById("firstDiv").insertBefore(newDiv);
}
function setBlue() {
var currentDivList=document.getElementsByClassName("TestDiv");
for(var i=0;i<currentDivList.length;i++){
currentDivList[i].style.color = "blue";
}
// What i can write here to change the TestDiv css class
// And after that, new (div)s will generate by new color(changed css class)
}
</script>
</head>
<body>
<div id="firstDiv" class="TestDiv">
test
</div>
<input type="button" value="add new div" onclick="addDiv();"/>
<input type="button" value="change color to blue" onclick="setBlue();"/>
</body>
</html>
最佳答案
我不建议即时添加或修改 CSS 规则,但有几种解决方案:
修改原来的CSS规则
<style id="myStyle"> .TestDiv { color:red; } </style> ... var myStyle = document.getElementById("myStyle"); myStyle.sheet.cssRules.item(0).cssText = ".TestDiv { color: blue }";
(我必须为样式标签分配一个 ID,否则我无法让它在 jsFiddle 环境中工作。使用
document.styleSheets[0]
应该同样可行。)将 CSS 规则添加到新创建的样式表(感谢 pawel !)
var style = document.createElement('style'); document.head.appendChild(style); style.sheet.addRule(".TestDiv", "color: blue");
将原始 CSS 文本添加到新创建的样式表: → jsFiddle
var sheet = document.createElement('style') sheet.innerHTML = ".TestDiv { color: blue }"; document.body.appendChild(sheet);
关于javascript - 有什么方法可以更改在浏览器中注册的 CSS 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19635582/