无法从结果 getComputedStyle 中获取边距属性的值
Unable to get value of margin property from result getComputedStyle
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()
函数不应计算速记属性(如 margin
、padding
)的值,而只计算普通属性(如 margin-top
、margin-bottom
、padding-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 等。
这里有一个堆栈溢出答案来支持这一点。
- 根据元素和容器大小计算边距
- 查找元素高度,包括边距
- 如何将CSS(特别是填充/边距)应用于select下拉菜单的选项或optgroup
- jquery返回边距为0的绝对中心
- 如何使用jQuery添加另一个对象的高度作为边距
- 如何根据主体高度动态更改元素边距顶部
- jQuery:粘滞的导航栏会更改边距
- 如何使边距不偏移我的网格
- 垂直与特定边距的顶部和底部对齐
- 尼沃滑块 尼沃控制导航边距
- 如果边距<“0px”,则更改边距
- Safari 的自动边距 + 平移 3d 1px 出血问题
- HTML表的边距/填充/边框(?)问题
- 边距填充和宽度属性的值
- 边距和输入元素边框之间的填充颜色
- 所有4页边距(上、右、下、左)的混合更少
- 在没有“位置”属性的情况下实现绝对定位,使用边距/填充
- 无法从结果 getComputedStyle 中获取边距属性的值
- 为什么JS遗漏了第四个边距属性
- IE8 jQ设置CSS属性(宽度或边距)被忽略