如何在纯 JavaScript 中获取 div 的边距值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14275304/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 16:14:55  来源:igfitidea点击:

How to get margin value of a div in plain JavaScript?

javascriptmargin

提问by YuC

I can get height in jQuery with

我可以在 jQuery 中获得高度

$(item).outerHeight(true);

but how do I with JS?

但是我如何使用 JS?

I can get the height of the li with

我可以得到 li 的高度

document.getElementById(item).offsetHeight

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

但是当我尝试 margin-top 时,我总是会得到“”:

document.getElementById(item).style.marginTop

回答by T.J. Crowder

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

style对象上的属性只是直接应用于元素的样式(例如,通过style属性或在代码中)。因此,.style.marginTop只有在您为该元素专门分配了某些内容(未通过样式表等分配)时,才会在其中包含某些内容。

To get the current calculated style of the object, you use either the currentStyleproperty (Microsoft) or the getComputedStylefunction (pretty much everyone else).

要获取对象的当前计算样式,您可以使用currentStyle属性 (Microsoft) 或getComputedStyle函数(几乎所有其他人)。

Example:

例子:

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

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

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

公平警告:您返回的内容可能不是以像素为单位的。例如,如果我p在 IE9 中的元素上运行上述内容,我会返回"1em".

Live Copy| Source

实时复制| 来源

回答by Snake

I found something very useful on this site when I was searching for an answer on this question. You can check it out at http://www.codingforums.com/javascript-programming/230503-how-get-margin-left-value.html. The part that helped me was the following:

当我在这个问题上寻找答案时,我在这个网站上发现了一些非常有用的东西。您可以在http://www.codingforums.com/javascript-programming/230503-how-get-margin-left-value.html 上查看。帮助我的部分如下:

var e = document.getElementById('yourElement');
var marLeft = getStyle(e, 'margin-left');
alert(marLeft);
/* and if a number needs to be in px... */
alert(marLeft + 'px');

////////////////////////////////////

/***
 * get live runtime value of an element's css style
 *   http://robertnyman.com/2006/04/24/get-the-rendered-style-of-an-element
 *     note: "styleName" is in CSS form (i.e. 'font-size', not 'fontSize').
 ***/
var getStyle = function (e, styleName) {
    var styleValue = "";
    if(document.defaultView && document.defaultView.getComputedStyle) {
        styleValue = document.defaultView.getComputedStyle(e, "").getPropertyValue(styleName);
    }
    else if(e.currentStyle) {
        styleName = styleName.replace(/\-(\w)/g, function (strMatch, p1) {
            return p1.toUpperCase();
        });
        styleValue = e.currentStyle[styleName];
    }
    return styleValue;
}

回答by Fabio Montefuscolo

Also, you can create your own outerHeightfor HTML elements. I don't know if it works in IE, but it works in Chrome. Perhaps, you can enhance the code below using currentStyle, suggested in the answer above.

此外,您可以outerHeight为 HTML 元素创建自己的元素。我不知道它是否适用于 IE,但它适用于 Chrome。也许,您可以使用currentStyle上面答案中建议的来增强下面的代码。

Object.defineProperty(Element.prototype, 'outerHeight', {
    'get': function(){
        var height = this.clientHeight;
        var computedStyle = window.getComputedStyle(this); 
        height += parseInt(computedStyle.marginTop, 10);
        height += parseInt(computedStyle.marginBottom, 10);
        height += parseInt(computedStyle.borderTopWidth, 10);
        height += parseInt(computedStyle.borderBottomWidth, 10);
        return height;
    }
});

This piece of code allow you to do something like this:

这段代码允许你做这样的事情:

document.getElementById('foo').outerHeight

According to caniuse.com, getComputedStyleis supported by main browsers (IE, Chrome, Firefox).

根据caniuse.com,主要浏览器(IE、Chrome、Firefox)都支持getComputedStyle