本文介绍了无法从结果getComputedStyle获取margin属性的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

getComputedStyle 的结果包含名为margin的属性,但该属性始终为空字符串()在Mozilla Firefox或Apple Safari中;但是,在Internet Explorer(和Google Chrome)中,margin属性包含预期值(即使在IE 6中)。使用返回对象的 getPropertyValue(margin)方法时返回相同的结果。

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.

怎么能我在Firefox和Safari中得到了保证金的计算值?

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

推荐答案

getComputedStyle()函数(例如 margin padding ),只评估手写属性(例如as margin-top margin-bottom padding-top )。在速记属性的情况下,它应该只返回一个空字符串。

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

此外,你可以看看,用于跨浏览器解决方案,使用 currentStyle 对于Internet Explorer

In addition, you can take a look at this link for a cross-browser solution, which uses currentStyle for internet explorer

这篇关于无法从结果getComputedStyle获取margin属性的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 07:46