Search code examples
javascriptcssprototypejscomputed-style

Simple getComputedStyle in Prototype JS?


Is there an easy cross-browser way to get computed style of an element in PrototypeJS, without checking document.defaultView... and other properties? ...so that the code looked like

var elt = $$('.xyz')[k],
    border = elt.getComputedStyle('border-bottom-width')

PrototypeJs provides getDimensions, -Width, and -Height methods that return computed dimensions, but there's no way to get other computed styles, like borders, backgrounds, etc.

I've found several stand-alone implementations of getComputedStyle, but maybe there's a patch/plugin for PrototypeJS that does that?


Solution

  • Prototype's getStyle method encapsulates most of the cross-browser computed style work you're looking for:

    var bgColor = $(element).getStyle('background-color');
    

    From the docs:

    This method looks up the CSS property of an element whether it was applied inline or in a stylesheet. It works around browser inconsistencies regarding float, opacity, which returns a value between 0 (fully transparent) and 1 (fully opaque), position properties (left, top, right and bottom) and when getting the dimensions (width or height) of hidden elements.

    However, this method will not return styles applied in a stylesheet in Internet Explorer <= 8, because it uses the getComputedStyle() method, which is the incorrect method for versions 8 and lower: http://www.quirksmode.org/dom/w3c_css.html