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

后端 未结 10 1719
悲&欢浪女
悲&欢浪女 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:22

    What about something like this (no jquery)? It's similar to @gdoron's answer but a little simpler. Tested it in IE9+, Firefox, and Chrome.

    function getAbsoluteHeight(el) {
      // Get the DOM Node if you pass in a string
      el = (typeof el === 'string') ? document.querySelector(el) : el; 
    
      var styles = window.getComputedStyle(el);
      var margin = parseFloat(styles['marginTop']) +
                   parseFloat(styles['marginBottom']);
    
      return Math.ceil(el.offsetHeight + margin);
    }
    

    Here is a working jsfiddle.

    0 讨论(0)
  • 2020-12-01 12:22
    var el = document.querySelector('div');
    
    var elHeight = el.offsetHeight;
    elHeight += parseInt(window.getComputedStyle(el).getPropertyValue('margin-top'));
    elHeight += parseInt(window.getComputedStyle(el).getPropertyValue('margin-bottom'));
    
    console.log(elHeight);
    

    https://jsfiddle.net/gbd47ox1/

    I think this solution is more readable, but none of the solutions presented account for sizes that aren't pixels... :(

    0 讨论(0)
  • 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;
    }
    <div id="myID">element</div>
    <div class="result"></div>

    0 讨论(0)
  • 2020-12-01 12:28

    Another functional solution using arrow functions:

    let el = document.querySelector('div');
    let style = window.getComputedStyle(el);
    let height = ['height', 'padding-top', 'padding-bottom']
            .map((key) => parseInt(style.getPropertyValue(key), 10))
            .reduce((prev, cur) => prev + cur);
    
    0 讨论(0)
提交回复
热议问题