Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

javascript - Unable to get value of margin property from result getComputedStyle

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)) });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...