How to Extract CSS Rule Values
How can you return a string containing all the contents of a CSS rule, like the format you'd see in an inline style? This can be done without knowing the specific content of the rule, avoiding the need to extract them by style name.
Consider the following CSS:
.test { width:80px; height:50px; background-color:#808080; }
To begin, we have the following code:
function getStyle(className) { var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules for(var x=0;x<classes.length;x++) { if(classes[x].selectorText==className) { //this is where I can collect the style information, but how? } } } getStyle('.test')
Building on scunliffe's answer and adapting from another source, we can enhance this code to extract the CSS rule values:
function getStyle(className) { var cssText = ""; var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules; for (var x = 0; x < classes.length; x++) { if (classes[x].selectorText == className) { cssText += classes[x].cssText || classes[x].style.cssText; } } return cssText; } alert(getStyle('.test'));
This code traverses the CSS rules, checking if the selector text matches the specified class name. For each matching rule, it collects the corresponding CSS text and accumulates it into the cssText variable. Finally, the function returns the accumulated CSS text, providing a string with the desired inline style format.
The above is the detailed content of How to Extract the Entire CSS Rule Content as a String?. For more information, please follow other related articles on the PHP Chinese website!