我可以以编程方式遍历CSS样式表吗?

时间:2014-01-08 00:34:56

标签: javascript jquery html css stylesheet

jQuery提供了一种漂亮,简洁的方法来遍历DOM ...我正在寻找的是一种遍历样式表,获取和设置已定义样式的属性的方法。

示例样式表

div {
    background: #FF0000;
    display: block;
}

.style {
    color: #00AA00;
    font-family: Verdana;
}

html body > nav.menu {
    list-style: none;
}

现在想象下面的代码就像jQuery for CSS ...

从CSS获取值

$("div").attr("background");
//returns #FF0000;

$(".style").attr("color");
// returns #00AA00;

$("html body > nav.menu").attr("color");
// returns undefined;

在CSS中设置值

$("div").attr("background", "#0000FF");

$(".style").attr("color", "#CDFF4E");

$("html body > nav.menu").attr("color", "#FFFFFF");

相当肯定这是不可能的......但只是在黑暗中狂奔!

2 个答案:

答案 0 :(得分:7)

我认为你可以,但界面比你想要的更加迟钝。

document.styleSheets返回一个StyleSheetList对象,它似乎在数组中表现得像。

因此document.styleSheets[0]会返回CSSStyleSheet个对象。期待有很多方法来分析它的内容。每个CSSStyleSheet都有一个cssRules属性,返回CSSRuleList

您可以自己遍历DOM api返回的各种类型的文档:https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet

答案 1 :(得分:2)

I just found a way to look through all of your style sheets, using jquery initially:

I have three stylesheets on my page, so first, I must identify the one I need to manipulate and I gave it an id: <style id="localRules">...</style>

Then, I use jQuery to initially find the id'd stylesheet I'm planning to change:

var sheetToChange = "localRules";
var sheets = $(document.styleSheets); 
// loop through all the stylesheets    
for (var thisSheet=0;thisSheet<sheets.length;thisSheet++){
     // find the right stylesheet to work on
     if(sheets[thisSheet].ownerNode.id == sheetToChange ){
          // cross browser referencing of css rules:
          var ruleSet = sheets[thisSheet].cssRules || sheets[thisSheet].rules;
          for (var thisRule=0;thisRule<ruleSet.length;thisRule++){
               // traverse in that style sheet for the rule you want to change, in this case, body:
               if(ruleSet[thisRule].selectorText == "body"){
                    ruleSet[thisRule].style.cursor = "pointer";
               }
           }
           break;               
     }
}

Hope this is helpful...it worked for me, but took a while to figure it out, especially because ownerNode is something I've never heard of before.