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

后端 未结 3 812
死守一世寂寞
死守一世寂寞 2020-12-24 02:06

I can get height in jQuery with

$(item).outerHeight(true);

but how do I with JS?

I can get the height of the li with



        
3条回答
  •  悲哀的现实
    2020-12-24 02:33

    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:

    /***
     * 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;
    }

提交回复
热议问题