我用一个简单的例子来解释这个问题。 我有以下的html页面。这很简单。有没有办法改变在浏览器中注册的CSS类
有一个名为TestDiv的CSS类和两个javascript函数。
- addDiv创建新的div并通过点击按钮追加到页面 “新增格”。
- setBlue是,我想改变的div的颜色有类TestDiv和功能我不知道如何。
你可以看到,我写了一些代码来改变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>
它正常工作对我来说:HTTP://的jsfiddle。 net/8M3xs/ – ComFreek
你想要的结果是什么。你没有正确解释你的问题 – MarsOne
我不认为你将能够改变一个页面的样式。你可能需要存储一个事实,即你有一个新的颜色,并在'addDiv()'函数中检查它以将其设置为新添加的div。 – Nunners