2012-05-28 12 views
43

Necesito toda la altura de un div, actualmente estoy usandoAltura completa de un elemento html (div) que incluye borde, relleno y margen?

document.getElementById('measureTool').offsetHeight 

offsetHeight - Devuelve la altura de un elemento, incluidos los bordes y el relleno en su caso, pero no en los márgenes

Pero uno de los elementos anidados dentro del div tiene un margin-top de 20%, por lo que obtengo una medición incorrecta. Intenté style.marginTop y scrollHeight sin éxito.

¿Cómo puedo obtener la altura completa (borde, relleno, margen) de un elemento (div) en javascript?

Si no hay otra forma, estoy de acuerdo con jQuery.

Respuesta

48

Si puede utilizar jQuery:

$('#divId').outerHeight(true) // gives with margins. 

jQuery docs

Por JavaScript básico que necesita para escribir mucho más (como siempre ...):

function Dimension(elmID) { 
    var elmHeight, elmMargin, elm = document.getElementById(elmID); 
    if(document.all) {// IE 
     elmHeight = elm.currentStyle.height; 
     elmMargin = parseInt(elm.currentStyle.marginTop, 10) + parseInt(elm.currentStyle.marginBottom, 10) + "px"; 
    } else {// Mozilla 
     elmHeight = document.defaultView.getComputedStyle(elm, '').getPropertyValue('height'); 
     elmMargin = parseInt(document.defaultView.getComputedStyle(elm, '').getPropertyValue('margin-top')) + parseInt(document.defaultView.getComputedStyle(elm, '').getPropertyValue('margin-bottom')) + "px"; 
    } 
    return (elmHeight+elmMargin); 
} 

Live DEMO

code source

+0

me gustaría mucho prefieren no (el proyecto no es realmente una página web). ¡Pero gracias por la solución de jquery y la respuesta rápida! :) – Edza

+1

@Edza. Para vanilla js, puede hacerlo [de esta manera] (http://www.webdeveloper.com/forum/archive/index.php/t-45522.html) – gdoron

+0

Muchas gracias, intentaré probarlo durante unos minutos antes de aceptar la respuesta – Edza

36

¿Qué tal algo como esto (sin jquery)? Es similar a la respuesta de @gdoron pero un poco más simple. Probado en IE9 +, Firefox y 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); 
} 

Aquí está un working jsfiddle.

4

antigua - de todos modos ... para todas las personas jQuery al prohibir y de acceso directo que hay aquí es algunas secuencias de comandos que se expande más los enfoques dimensión/getabsoluteheight de las otras respuestas:

function getallinheight(obj) { 
    var compstyle=(typeof window.getComputedStyle==='undefined')?obj.currentStyle:window.getComputedStyle(obj); 
    var marginTop=parseInt(compstyle.marginTop); 
    var marginBottom=parseInt(compstyle.marginBottom); 
    var borderTopWidth=parseInt(compstyle.borderTopWidth); 
    var borderBottomWidth=parseInt(compstyle.borderBottomWidth); 
    return obj.offsetHeight+ 
     (isNaN(marginTop)?0:marginTop)+(isNaN(marginBottom)?0:marginBottom)+ 
     (isNaN(borderTopWidth)?0:borderTopWidth)+(isNaN(borderBottomWidth)?0:borderBottomWidth); 
} 
alert(getallinheight(document.getElementById('measureTool'))); 
8
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/

Creo que esta solución es más legible, pero ninguna de las soluciones presentadas cuenta para tamaños que no son píxeles ... :(

3

Otra solución funcional utilizando 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

Es posible que desee agregar 'margin-top' y' margin-bottom' – Martin

Cuestiones relacionadas