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

后端 未结 3 813
死守一世寂寞
死守一世寂寞 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

    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.).

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

    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 p element in IE9, I get back "1em".

    Live Copy | Source

提交回复
热议问题