【问题标题】:How to get margin value of a div in plain JavaScript?如何在纯 JavaScript 中获取 div 的边距值?
【发布时间】:2012-12-25 20:47:38
【问题描述】:

我可以在 jQuery 中使用

$(item).outerHeight(true);

但是我如何使用 JS 呢?

我可以得到 li 的高度

document.getElementById(item).offsetHeight

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

document.getElementById(item).style.marginTop

【问题讨论】:

    标签: javascript margin


    【解决方案1】:

    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"

    Live Copy | Source

    【讨论】:

    • 谢谢 T.J.,我在 FF 和 Chrome 上试过了,它可以工作。我一开始以为getComputedStyle()是元素节点的方法,原来是window的方法。我稍后会在 IE 上尝试。
    • 正如你所说,这仅在原始单位为“px”时才有效。您有任何解决方案来获得真正的价值吗?
    • @vsync:不,无论原始值的单位如何,它都可以工作,但是您收到的内容很可能是(或可能不是)以像素为单位。我不知道有一种方法可以可靠地获得非像素值,而不是自己通过 CSS 规则。
    • 方法getComputedStyle()将始终返回“解析值”,即它始终返回一个像素值,与CSS规则中使用的单位无关
    【解决方案2】:

    此外,您可以为 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, getComputedStyle,主流浏览器(IE、Chrome、Firefox)都支持。

    【讨论】:

    • 我认为 IE 不支持 window.getComputedStyle 方法,谢谢。
    • getComputedStyle 适用于 IE ≥ 9
    • 但是我生活在一个你必须处理IE6的国家(┬_┬)
    • getComputedStyle 非常慢。你应该避免像这样不必要地回忆它。
    • @JosephLennox 你知道 jQuery 是怎么做的吗?
    【解决方案3】:

    当我在寻找这个问题的答案时,我在这个网站上发现了一些非常有用的东西。你可以在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>

    【讨论】:

    • 谢谢,你的方法和 T.J. 类似。 Crowder,但你把它包装成一个函数。 ^_^
    【解决方案4】:

    这是我的解决方案:

    第 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)
    console.log(marginTopNumber)
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-26
      • 1970-01-01
      • 2014-08-26
      • 2013-03-14
      • 2015-03-29
      • 1970-01-01
      • 2012-10-26
      相关资源
      最近更新 更多