How to get the height of a DIV considering inner element's margins?

前端 未结 11 3311
日久生厌
日久生厌 2021-02-20 04:20

Consider de following markup:

11条回答
  •  长情又很酷
    2021-02-20 04:44

    WARNING WARNING clientHeight almost works but doesn't include margins :(

    Just thought I'd add that I've been trying this today, and while nahumsilva & plodder almost have it right (nahumsilva's version appears to be more cross-browser {plodder's doesn't appear to work in Chrome/WebKit, but I'm no expert on these things}), they've both missed that an element may have computed style elements that aren't defined by it's own style.

    This was driving me nuts - I was wondering where my

    elements were getting an extra 16px of margin height - until I realised it was coming from the computed style.

    So, long story short, an approach like nahumsilva / plodder worked for me, with the added proviso that you should get the element's computed style with window.getComputedStyle( element, null ), which returns a CSSStyleDeclaration object (like element.style). element.offsetHeight / element.clientHeight should give you the height without margins, so the whole thing looks like:

    var cstyle = window.getComputedStyle( element, null );
    var elementHeight = element.offsetHeight +
    Number( cstyle.marginBottom.replace(/[^\d\.]/g, '') ) +
    Number( cstyle.marginTop.replace(/[^\d\.]/g, '') );
    

提交回复
热议问题