make iframe height dynamic based on content inside- JQUERY/Javascript

前端 未结 20 2223
情书的邮戳
情书的邮戳 2020-11-22 07:42

I am loading an aspx web page in an iframe. The content in the Iframe can be of more height than the iframe\'s height. The iframe should not have scroll bars.

I have

20条回答
  •  無奈伤痛
    2020-11-22 08:09

    There are four different properties you can look at to get the height of the content in an iFrame.

    document.documentElement.scrollHeight
    document.documentElement.offsetHeight
    document.body.scrollHeight
    document.body.offsetHeight
    

    Sadly they can all give different answers and these are inconsistant between browsers. If you set the body margin to 0 then the document.body.offsetHeight gives the best answer. To get the correct value try this function; which is taken from the iframe-resizer library that also looks after keeping the iFrame the correct size when the content changes,or the browser is resized.

    function getIFrameHeight(){
        function getComputedBodyStyle(prop) {
            function getPixelValue(value) {
                var PIXEL = /^\d+(px)?$/i;
    
                if (PIXEL.test(value)) {
                    return parseInt(value,base);
                }
    
                var 
                    style = el.style.left,
                    runtimeStyle = el.runtimeStyle.left;
    
                el.runtimeStyle.left = el.currentStyle.left;
                el.style.left = value || 0;
                value = el.style.pixelLeft;
                el.style.left = style;
                el.runtimeStyle.left = runtimeStyle;
    
                return value;
            }
    
            var 
                el = document.body,
                retVal = 0;
    
            if (document.defaultView && document.defaultView.getComputedStyle) {
                retVal =  document.defaultView.getComputedStyle(el, null)[prop];
            } else {//IE8 & below
                retVal =  getPixelValue(el.currentStyle[prop]);
            } 
    
            return parseInt(retVal,10);
        }
    
        return document.body.offsetHeight +
            getComputedBodyStyle('marginTop') +
            getComputedBodyStyle('marginBottom');
    }
    

提交回复
热议问题