我正在寻找将 html 元素 css 边距值转换为绝对像素的最简单和跨浏览器的方法。例如说边距是“自动”。 我不能使用任何 js 框架。
最佳答案
您想使用 window.getComputedStyle
方法:
var style = window.getComputedStyle(element, null);
// style.marginLeft
这是一个工作演示:http://jsfiddle.net/VxccZ/
更新
对于 IE 8 及更早版本(不支持此方法),请使用元素的 currentStyle
属性:
var style = element.currentStyle;
// style.marginLeft
总结:
var getMarginLeft = function (element) {
var style;
if (window.getComputedStyle) { style = window.getComputedStyle(element, null); }
else { style = element.currentStyle; }
return style.marginLeft;
};
我不是 100% 确定 currentStyle
具有 margin: auto
的数值。你将不得不自己尝试。我自己无法在 Mac 上执行此操作。
关于javascript - 如何使用纯 javascript 将 css 边距值转换为像素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13308568/