假设我已经声明了一些样式(直接在我的 html 文档上或通过外部 css 文件):
<style>
.Red { background-color: red; }
.Green { background-color: green; }
.Blue { background-color: blue; }
</style>
在我的 javascript 代码中,我想列出数组或任何其他形式的所有可用样式
function getAvailableStyleNames(){
return ["Red", "Green", "Blue"]; // Dummy code. the answer would go here...
}
谢谢!
最佳答案
这是你想要的功能:
CSS
.Red { background-color: red; }
.Green { background-color: green; }
.Blue { background-color: blue; }
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 />";
}
}
HTML
<input onclick="PrintRules()" type="button" value="Print Rules" /><br />
Rules:
<div id="rules"></div>
关于javascript - 列出所有可用的 CSS 样式 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17813016/