Getting an element's inner height

后端 未结 5 608
说谎
说谎 2020-12-08 10:04

How do you get an element\'s inner height, without padding and borders?

No jQuery, just pure JS, and a cross-browser solution (IE7 included)

5条回答
  •  一个人的身影
    2020-12-08 10:45

    EDIT from comments:

    http://jsfiddle.net/hTGCE/1/ (a bit more code then expected)

    in the internet you find functions like this:

      function getRectangle(obj) {
    
              var r = { top: 0, left: 0, width: 0, height: 0 };
    
              if(!obj)
                 return r;
    
              else if(typeof obj == "string")
                 obj = document.getElementById(obj);
    
    
              if(typeof obj != "object")
                 return r;
    
              if(typeof obj.offsetTop != "undefined") {
    
                 r.height = parseInt(obj.offsetHeight);
                 r.width  = parseInt(obj.offsetWidth);
                 r.left = r.top = 0;
    
                 while(obj && obj.tagName != "BODY") {
    
                    r.top  += parseInt(obj.offsetTop);
                    r.left += parseInt(obj.offsetLeft);
    
                    obj = obj.offsetParent;
                 }
              }
              return r;
           }
    

    if you want to subtract the padding / border-width is set in the css-file and not dynamic in the style attribute:

        var elem = document.getElementById(id);
        var borderWidth = 0;
    
              try {
                 borderWidth = getComputedStyle(elem).getPropertyValue('border-top-width');
    
                 } catch(e) {
    
                 borderWidth = elem.currentStyle.borderWidth;
              } 
        borderWidth = parseInt(borderWidth.replace("px", ""), 10);
    

    and with the padding the same. then you calculate it.

提交回复
热议问题