无法从结果 getComputedStyle 中获取边距属性的值

Unable to get value of margin property from result getComputedStyle

本文关键字:取边距 属性 获取 结果 getComputedStyle      更新时间:2023-09-26

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

如何在 Firefox 和 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()函数不应计算速记属性(如 marginpadding)的值,而只计算普通属性(如 margin-topmargin-bottompadding-top )。在速记属性的情况下,它应该只返回一个空字符串。

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

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

您可以使用此垫片,适用于所有浏览器:参考此

使用 currentStyle for Internet Explorer。

getComputedStyle用于其他浏览器

我尝试过这样的事情,在所有浏览器中对我来说都是worKing。

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

获取此接口的属性等效于调用 CSSStyleDeclaration接口的getPropertyValue方法

http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration

正如David Flanagan在"Javascript权威指南"中指出的那样,问题仅与计算样式有关:

  • 不计算快捷方式属性,仅计算它们所基于的基本属性。不要查询边距属性, 例如,但使用 marginLeft、marginTop 等。

这里有一个堆栈溢出答案来支持这一点。