Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to get value of margin property from result getComputedStyle

Tags:

javascript

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
like image 758
dasdasdasdasd Avatar asked Sep 07 '13 17:09

dasdasdasdasd


People also ask

What does the window getComputedStyle() method return?

The Window. getComputedStyle() method returns an object containing the values of all CSS properties of an element, after applying active stylesheets and resolving any basic computation those values may contain.

How do you make a margin in HTML?

Definition and Usage Two values, like: div {margin: 50px 10px} - the top and bottom margins will be 50px, left and right margins will be 10px. Three values, like: div {margin: 50px 10px 20px}- the top margin will be 50px, left and right margin will be 10px, bottom margin will be 20px.


2 Answers

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

like image 101
nasser-sh Avatar answered Sep 21 '22 08:09

nasser-sh


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

like image 43
HIRA THAKUR Avatar answered Sep 20 '22 08:09

HIRA THAKUR