Adjust width and height of iframe to fit with content in it

前端 未结 30 2749
旧时难觅i
旧时难觅i 2020-11-22 02:09

I need a solution for auto-adjusting the width and height of an iframe to barely fit its content. The point is that t

30条回答
  •  独厮守ぢ
    2020-11-22 02:35

    I figured out another solution after some experimenting. I originally tried the code marked as 'best answer' to this question and it didn't work. My guess is because my iframe in my program at the time was dynamically generated. Here is the code I used (it worked for me):

    Javascript inside the iframe that is being loaded:

    window.onload = function()
        {
            parent.document.getElementById('fileUploadIframe').style.height = document.body.clientHeight+5+'px';
            parent.document.getElementById('fileUploadIframe').style.width = document.body.clientWidth+18+'px';
        };
    

    It is necessary to add 4 or more pixels to the height to remove scroll bars (some weird bug/effect of iframes). The width is even stranger, you are safe to add 18px to the width of the body. Also make sure that you have the css for the iframe body applied (below).

    html, body {
       margin:0;
       padding:0;
       display:table;
    }
    
    iframe {
       border:0;
       padding:0;
       margin:0;
    }
    

    Here is the html for the iframe:

    
    

    Here is all the code within my iframe:

    
    
    
        
        File Upload
        
        
    
    
        This is a test.
    testing

    I have done testing in chrome and a little in firefox (in windows xp). I still have more testing to do, so please tell me how this works for you.

提交回复
热议问题