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

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

Consider de following markup:

11条回答
  •  自闭症患者
    2021-02-20 04:36

    Try using clientHeight

    var outerElement = document.getElementById("outerElement");
    if(outerElement.clientHeight) {
    alert("Height is "+outerElement.clientHeight+"px");
    }
    else { alert("Old browser?"); }
    

    I know what you're thinking... "this won't work!" and alas, it doesn't... but if you do something like add a border to outerElement... even for just a moment...

    var outerElement = document.getElementById("outerElement");
    outerElement.style.border = "1px solid black";
    var height = outerElement.clientHeight;
    outerElement.style.border = "none";
    alert("Height is "+height+"px");
    

    Not the most beautiful solution but it works, and if you can figure out why it works (I sure as hell don't know :P) you might be closer to a good solution...

    Some older browsers may not support it though... you'd have to look into it; I can't list 'em.

提交回复
热议问题