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

问题描述 投票:0回答:4

我可以在 jQuery 中使用

获取高度
$(item).outerHeight(true);

但是我该如何使用 JS 呢?

我可以用

得到李的高度
document.getElementById(item).offsetHeight

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

document.getElementById(item).style.marginTop
javascript margin
4个回答
166
投票

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

要获取对象的当前计算样式,您可以使用

currentStyle
属性 (Microsoft) 或
getComputedStyle
函数(几乎所有其他人)。

示例:

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

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

公平警告:您返回的内容可能不是像素。例如,如果我在 IE9 中的

p
元素上运行上述内容,我会返回
"1em"

实时复制 | 来源


12
投票

此外,您还可以为 HTML 元素创建自己的

outerHeight
。我不知道它在 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;
    }
});

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

document.getElementById('foo').outerHeight

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


11
投票

这是我的解决方案:

第1步:选择元素

第 2 步:使用 getComputedStyle 并向其提供元素

第 3 步:现在访问所有属性

const item = document.getElementbyId('your-element-id');
const style= getComputedStyle(item);
const itemTopmargin = style.marginTop;
console.log(itemTopmargin)

它将为您提供 px 单位的边距,例如您可能不想要的“16px”。 您可以使用

parseInt()

提取值
const marginTopNumber = parseInt(itemTopmargin, 10)
console.log(marginTopNumber)

它只会给你数值(没有任何单位)。


9
投票

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

/***
 * 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;
}
////////////////////////////////////
var e = document.getElementById('yourElement');
var marLeft = getStyle(e, 'margin-left');
console.log(marLeft);    // 10px
#yourElement {
  margin-left: 10px;
}
<div id="yourElement"></div>

© www.soinside.com 2019 - 2024. All rights reserved.