Can I programmatically traverse a CSS stylesheet?

怎甘沉沦 提交于 2019-12-10 15:08:28

问题


jQuery provides a nice, neat way to traverse the DOM...what I'm looking for is a way to traverse a stylesheet, getting and setting attributes for the defined styles.

Example Stylesheet

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

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

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

Now imagine the following code is like jQuery for CSS...

Getting values from the CSS

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

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

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

Setting values in the CSS

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

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

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

Fairly certain this is not possible...but just a wild stab in the dark!


回答1:


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.




回答2:


I think you can, but the interface is more obtuse than you probably want.

document.styleSheets returns a StyleSheetList object that seems to behave in an array like way.

So document.styleSheets[0] returns a CSSStyleSheet object. Look to have lots of ways to analyze it's content. And each CSSStyleSheet has a cssRules property which returns a CSSRuleList.

And you can traverse the docs on the various types return by the DOM api from there yourself: https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet



来源:https://stackoverflow.com/questions/20984885/can-i-programmatically-traverse-a-css-stylesheet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!