让我们假设我已经声明了一些样式(直接在我的html文档或外部css文件中):
<style>
.Red { background-color: red; }
.Green { background-color: green; }
.Blue { background-color: blue; }
</style>
在我的javascript代码中,我想列出Array中的所有可用样式或任何其他形式
function getAvailableStyleNames(){
return ["Red", "Green", "Blue"]; // Dummy code. the answer would go here...
}
谢谢!
答案 0 :(得分:5)
这是您想要的功能:
.Red { background-color: red; }
.Green { background-color: green; }
.Blue { background-color: blue; }
function PrintRules() {
var rules = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
var rulesDiv = document.getElementById("rules");
for(var x=0;x<rules.length;x++) {
rulesDiv.innerHTML += rules[x].selectorText + "<br />";
}
}
<input onclick="PrintRules()" type="button" value="Print Rules" /><br />
Rules:
<div id="rules"></div>