Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
191
rated 0 times [  198] [ 7]  / answers: 1 / hits: 39418  / 11 Years ago, sat, september 7, 2013, 12:00:00

The result of a getComputedStyle contains a property named margin, but the property is always an empty string () in Mozilla Firefox or Apple Safari; however, in Internet Explorer (and Google Chrome) the margin property contains the expected value (even in IE 6). The same result is returned when using the getPropertyValue(margin) method of the returned object.



How can I get the computed value of the margin in Firefox and Safari?





var el = document.body.appendChild(document.createElement('div'));
el.style.margin = '2px';
console.log(getComputedStyle(el, null).margin === ); // false in IE and Chrome
console.log(getComputedStyle(el, null).getPropertyValue(margin) === ); // same




More From » javascript

 Answers
2

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


[#75838] Thursday, September 5, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jazminuniquer

Total Points: 63
Total Questions: 121
Total Answers: 96

Location: Cambodia
Member since Thu, May 21, 2020
4 Years ago
;