列出所有可用的CSS样式javascript

lvi*_*ani 2 html javascript css

让我们想象一下我已经声明了一些样式(直接在我的html文档或外部css文件中):

<style>
.Red { background-color: red; }
.Green { background-color: green; }
.Blue { background-color: blue; }
</style>
Run Code Online (Sandbox Code Playgroud)

在我的javascript代码中,我想列出Array或任何其他形式的所有可用样式

function getAvailableStyleNames(){
  return ["Red", "Green", "Blue"]; // Dummy code. the answer would go here...
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

Akr*_*res 5

这是你想要的功能:

CSS

.Red { background-color: red; }
.Green { background-color: green; }
.Blue { background-color: blue; }
Run Code Online (Sandbox Code Playgroud)

JS

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 />";
    }
}
Run Code Online (Sandbox Code Playgroud)

HTML

<input onclick="PrintRules()" type="button" value="Print Rules" /><br />
Rules:
<div id="rules"></div>
Run Code Online (Sandbox Code Playgroud)