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

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

Consider de following markup:

11条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-20 04:43

    ok also not pretty but this is how I do it (disclaimer: I stole this from somewhere once)

    var height = elem.clientHeight + getBufferHeight(elem, true);
    
    function getBufferHeight(elem, includeMargins) {
        if (!elem.visible()) {
            return 0;
        }
        //do new Number instead of parseFloat to avoid rounding errors 
        var result = 0;
        if (includeMargins) {
            result =   
                new Number(elem.getStyle('marginTop').replace(/[^\d\.]/g, '')).ceil() +  
                new Number(elem.getStyle('marginBottom').replace(/[^\d\.]/g, '')).ceil();
        }     
        result +=
            new Number(elem.getStyle('borderBottomWidth').replace(/[^\d\.]/g, '')).ceil() +
            new Number(elem.getStyle('borderTopWidth').replace(/[^\d\.]/g, '')).ceil() +    
            new Number(elem.getStyle('paddingTop').replace(/[^\d\.]/g, '')).ceil() +
            new Number(elem.getStyle('paddingBottom').replace(/[^\d\.]/g, '')).ceil();                        
        return result;
    }
    

提交回复
热议问题