如何在纯JavaScript中获取div的保证金值? [英] How to get margin value of a div in plain JavaScript?

查看:63
本文介绍了如何在纯JavaScript中获取div的保证金值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以通过

$(item).outerHeight(true);

但是我如何使用JS?

but how do I with JS?

我可以得到李的高度

document.getElementById(item).offsetHeight

但是当我尝试使用margin-top时,我总是会收到":

but i will always get "" when I try margin-top:

document.getElementById(item).style.marginTop

推荐答案

style对象上的属性只是直接应用于元素的样式(例如,通过style属性或代码).因此,.style.marginTop仅在您有专门分配给该元素的内容(而不是通过样式表等分配)的情况下存在.

The properties on the style object are only the styles applied directly to the element (e.g., via a style attribute or in code). So .style.marginTop will only have something in it if you have something specifically assigned to that element (not assigned via a style sheet, etc.).

要获取对象的当前计算样式,请使用 getComputedStyle 功能(几乎其他所有人).

To get the current calculated style of the object, you use either the currentStyle property (Microsoft) or the getComputedStyle function (pretty much everyone else).

示例:

var p = document.getElementById("target");
var style = p.currentStyle || window.getComputedStyle(p);

display("Current marginTop: " + style.marginTop);

警告:您得到的结果可能不是以像素为单位.例如,如果我在IE9中的p元素上运行上述命令,则会返回"1em".

Fair warning: What you get back may not be in pixels. For instance, if I run the above on a p element in IE9, I get back "1em".

实时复制 | 来源

这篇关于如何在纯JavaScript中获取div的保证金值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆