Sources:
- Get the height of an element minus padding, margin, border widths
- JavaScript DOM / Getting the Width and Height of an Element
- MDN WebDocs – element.offsetHeight
Dégageage du padding avec getComputedStyle
Faire un console.log(computedStyle);
vous donnera une liste de toutes les données récupérées via la méthode getComputedStyle
et que vous pourrez exploiter ensuite.
1 2 3 4 5 6 7 |
var computedStyle = getComputedStyle(element); elementHeight = element.clientHeight; // height with padding elementWidth = element.clientWidth; // width with padding elementHeight -= parseFloat(computedStyle.paddingTop) + parseFloat(computedStyle.paddingBottom); elementWidth -= parseFloat(computedStyle.paddingLeft) + parseFloat(computedStyle.paddingRight); |
Dans la pratique:
Je veux récupérer la hauteur du contenu de l’élément de DOM .page-leftColumn
sans le padding:
1 2 3 4 |
let $leftColumn = document.querySelector('.page-leftColumn'), computedStyle = getComputedStyle($leftColumn), leftColumnHeight = $leftColumn.clientHeight - (parseFloat(computedStyle.paddingTop) + parseFloat(computedStyle.paddingBottom)); // console.log(leftColumnHeight); |
Tenir compte de la scrollbar
Voir aussi ici pour ce bout de code modifié pour tenir compte de la scrollbar:
1 2 3 4 5 6 7 8 9 10 11 |
var cs = getComputedStyle(element); var paddingX = parseFloat(cs.paddingLeft) + parseFloat(cs.paddingRight); var paddingY = parseFloat(cs.paddingTop) + parseFloat(cs.paddingBottom); var borderX = parseFloat(cs.borderLeftWidth) + parseFloat(cs.borderRightWidth); var borderY = parseFloat(cs.borderTopWidth) + parseFloat(cs.borderBottomWidth); // Element width and height minus padding and border elementWidth = element.offsetWidth - paddingX - borderX; elementHeight = element.offsetHeight - paddingY - borderY; |