Cross-browser (IE8-) getComputedStyle with Javascript?
cross-browser, internet-explorer, javascript, styles
Solution
You don't want to use jquery but there's nothing preventing you from peeking into the code and see how they dealt with it :-)
Inside jquery code there's a reference about this comment which seems to the point (read also the whole article). Here's the jquery code that should deal with your problem:
else if ( document.documentElement.currentStyle ) {
curCSS = function( elem, name ) {
var left, rsLeft,
ret = elem.currentStyle && elem.currentStyle[ name ],
style = elem.style;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && style[ name ] ) {
ret = style[ name ];
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// but not position css attributes, as those are proportional to the parent element instead
// and we can't measure the parent instead because it might trigger a "stacking dolls" problem
if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {
// Remember the original values
left = style.left;
rsLeft = elem.runtimeStyle && elem.runtimeStyle.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
elem.runtimeStyle.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
elem.runtimeStyle.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
Problem
Since IE8 does not support `getComputedStyle`, we can only use `currentStyle`. However, it does not return the real "computed" value for some properties. For example: ``` <style type="text/css"> #div {/* no properties are defined here */} </style> ``` ``` <div id="div">div</div> ``` ``` // returns "medium" instead of 0px document.getElementById('div').currentStyle.borderLeftWidth // returns "auto" instead of 0px document.getElementById('div').currentStyle.marginLeft // returns "undefined" instead of 1 document.getElementById('div').currentStyle.opacity ``` Does anyone have a cross-browser solution for all properties without using jQuery or other Javascript libraries?