Since the original getComputedStyle(..) function was posted in a previous blog entry, I'm not going to bother posting it again. Instead, I'll only post the updated version below.
if (!sstchur.web) { sstchur.web = {}; }
if (!sstchur.web.xb) { sstchur.web.xb = {}; }
sstchur.web.xb.getComputedStyle = function(_elem, _style)
{
var nonPixels = /(em|ex|pt|%)$/;
var computedStyle;
if (typeof _elem.currentStyle != 'undefined')
{
computedStyle = _elem.currentStyle;
var val = computedStyle[_style];
if (nonPixels.test(val))
{ return sstchur.web.xb.convertToPixels(val, _elem); }
}
else
{ computedStyle = document.defaultView.getComputedStyle(_elem, null); }
return computedStyle[_style];
}
There aren't many changes to this function. The only thing required is to utilize our convertToPixels(..) function if we're in the if (typeof _elem.currentStyle != 'undefined') block. However, we don't want to do this unconditionally. It's perfectly feasible that we might want to retrieve a computed style that has nothing to do with units (a color value for example: #369 or something like that). In this case, we absolutely don't want to call convertToPixels(..) becuase it would fail (probably with a js error).
To avoid such a scenerio, we sipmly create a regular expression matching any string that ends with any of: 'em', 'ex', 'pt' or '%'. If the computed style ends with one of those units, then it's probably safe to utilize convertToPixels(..).
By taking advantage of the convertToPixels(..) function we just wrote, our sstchur.web.xb.getComputedStyle(..) is edging ever closer to the utopian dream of W3C compliance. It's still not perfect mind you. A perfect function would not only normalize all units to pixels, but also normalize all color values from hex codes, like #fff to rgb values, like rgb(255, 255, 255).
Still, just having our function return us a consisten unit across browsers is a major step in the right direction.
Comments welcome.
Pages: 1 2
4 Responses
This has been very helpful. Thanks!
This is perfect: I'm writing a image replacement solution that will benefit hugely from this. Thanks for sharing it!
This returns height of the element in pixels.
In firefox 2.0.0.14 and IE 7.
document.getElementById('div1').scrollHeight
It seems to me that the browsers are implemented the way to complicate the things as much as possible. You must cheat all the time
)
Vlado,
Thanks for the tip. I've only run across .scrollHeight once or twice and haven't really utilized it much. Do you know if it give the overall height of an element, including borders and padding? Or just the internal height of the element (minus borders and padding)?
What does IE6 think of this property?