How to read the ACTUAL CSS rule for border radius
I am wrapping an auto-generated div around an image and I need to apply some style from the image to the div.
How can I read / get the border radius CSS rule affecting the image?
For example, if the CSS sets the border radius to 30px
, it should return "30px", and if it does 50%
, it should return "50%" - I want the actual rule, not just the pixel value
source to share
Here is the code I wrote to get the actual text of the css rule:
function getCssRule(selector, ruleName) {
var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
for (var x = 0; x < classes.length; x++) {
if (classes[x].selectorText == selector) {
if(classes[x].cssText){
var text = classes[x].cssText.substr(classes[x].cssText.indexOf(ruleName));
text = text.substr(text.indexOf(':')+1, text.indexOf(';') - text.indexOf(':') - 1);
if(text[0] == " ")
text = text.substr(1);
return text;
}
}
}
}
console.log(getCssRule('.class', "margin"));
There are some css processing issues that make it difficult to use:
1. If your document contains multiple stylesheets, the index of the stylesheet used depends on the insertion of your rules (it is mostly 0)
2. browsers may handle some rules differently and reorganize them (for example, in chrome, the radius border is split into top and left radius borders, top right and bottom radius borders, bottom left radius borders, and -bottom-right radius borders)
working fiddle: fiddle
source to share