Access CSS class using javascript

How can I access the style declaration of an element specified using an external or inline style sheet. For example: how to access the width property of an element that is defined in the inline stylesheet using the id selector. I know that a CSSRules object can do this ... But it depends on the browser. For ex: in chrome, an object has a null value ... So what is a browser independent way to do this?

+3
source share
2 answers

It really depends on the browser ... I have some code that I use to create a text area with auto-extension adapted from the found there code .

, $ Prototype.

function getStyleFromCss(el, style) {
    /* Hack required by IE */
    var value = $(el).getStyle(style);
    if (!value) {
        /* For other browsers. Actually this equals 'window'. Use that
         *  if Opera fails on you. */
        if(document.defaultView) {
            value = document.defaultView.getComputedStyle(el, null).
                getPropertyValue(style);
            // for IE
        } else if(el.currentStyle) {
            value = el.currentStyle[style];
        }
    }
    if(value.length > 0){
        /* if the value returned has the word px in it, we check for
         *  the letter x */
        if (value.charAt(value.length-1) == "x") {
            value = parseInt(value.substring(0, value.length-2));
        }
    }
    return value;
}

getStyle() Prototype , .

getStyle: function(element, style) {
  element = $(element);
  style = style == 'float' ? 'cssFloat' : style.camelize();
  var value = element.style[style];
  if (!value || value == 'auto') {
    var css = document.defaultView.getComputedStyle(element, null);
    value = css ? css[style] : null;
  }
  if (style == 'opacity') return value ? parseFloat(value) : 1.0;
  return value == 'auto' ? null : value;
},
+2

, IE IE9 -. , , , - :

function getStyle(el, cssprop) {
    if (document.defaultView && document.defaultView.getComputedStyle)
        return document.defaultView.getComputedStyle(el, null)[cssprop];
    else //IE
        return el.currentStyle[cssprop];
}
+2

All Articles