The result of a getComputedStyle
contains a property named \"margin\", but the property is always an empty string (\"\"
) in Mozilla Firefox or Appl
var elem = document.getElementById("your-div");
if (elem.currentStyle) {
var margin = elem.currentStyle.margin;
} else if (window.getComputedStyle) {
var margin = window.getComputedStyle(elem, null).getPropertyValue("margin");
}
alert(margin);
you can use this shim,works for all browsers:refer this
use currentStyle for Internet Explorer.
use getComputedStyle for other browsers
I tried something like this and it is worKing for me in all browsers
var elem = document.createElement('div');
var t=document.createTextNode('M')
elem.appendChild(t);
document.body.appendChild(elem);
var myfontSize = getStyle(elem,"fontSize")
alert(myfontSize)
function getStyle(elem,prop){
if (elem.currentStyle) {
var res= elem.currentStyle.margin;
} else if (window.getComputedStyle) {
if (window.getComputedStyle.getPropertyValue){
var res= window.getComputedStyle(elem, null).getPropertyValue(prop)}
else{var res =window.getComputedStyle(elem)[prop] };
}
return res;
}
Getting an attribute of this interface is equivalent to calling the getPropertyValue method of the CSSStyleDeclaration interface
http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration
The problem as David Flanagan precised in 'Javascript the definitive guide' is about computed styles only :
- Shortcut properties are not computed, only the fundamental properties that they are based on. Don’t query the margin property, for example, but use marginLeft, marginTop, and so on.
And here's a stackoverflow answer to back this up.
The getComputedStyle()
function should not evaluate the values of shorthand properties (such as margin
, padding
), only longhand properties (such as margin-top
, margin-bottom
, padding-top
). In the case of shorthand properties it should only return an empty string.
var el = document.body.appendChild(document.createElement('div'));
el.style.margin = '2px';
var computed = getComputedStyle(el);
var longhands = ['margin-top', 'margin-bottom', 'margin-left', 'margin-right'];
longhands.forEach(function(e) { console.log(e + ': ' + computed.getPropertyValue(e)) });
In addition, you can take a look at this link for a cross-browser solution, which uses currentStyle
for internet explorer