Full height of a html element (div) including border, padding and margin?

后端 未结 10 1769
悲&欢浪女
悲&欢浪女 2020-12-01 11:42

I need the full height of a div, I\'m currently using

document.getElementById(\'measureTool\').offsetHeight

offsetHeig

10条回答
  •  北荒
    北荒 (楼主)
    2020-12-01 12:23

    Vanilla JavaScript ECMAScript 5.1

    • element.getBoundingClientRect() returns a DOMRect object which contains height (including padding & border)
    • window.getComputedStyle(element) returns an object with all CSS properties after applying active stylesheets and performed any computation (if present)

    var element = document.getElementById('myID'),
        height = element.getBoundingClientRect().height,
        style = window.getComputedStyle(element);
        
    // height: element height + vertical padding & borders
    // now we just need to add vertical margins
    height = ["top", "bottom"]
      .map(function(side) {
        return parseInt(style['margin-' + side], 10)
      })
      .reduce(function(total, side) {
        return total + side
      }, height)
      
    // result: compare with devtools computed measurements
    document.querySelector('.result').innerText = 'Total height is: ' + height + 'px';
    #myID {
      padding: 10px 0 20px;
      border-top: solid 2px red;
      border-bottom: solid 3px pink;
      margin: 5px 0 7px;
      background-color: yellow;
    }
    
    .result {
      margin-top: 50px;
    }
    element

提交回复
热议问题