auto re-sizing iframe that dynamically changing he

2019-02-21 01:24发布

问题:

I know there's a lot of post about re-sizing iframe but all i found is this code:

<script type="text/javascript" language="JavaScript">
<!--            
        function autoResize(id) {
            var newheight;
            var newwidth;

            if (document.getElementById) {
                newheight = document.getElementById(id).contentWindow.document.body.scrollHeight;
                newwidth = document.getElementById(id).contentWindow.document.body.scrollWidth;
            }
            document.getElementById(id).height = (newheight);
            document.getElementById(id).width = (newwidth);
        };
//-->
</script>

and this is the sample mark-up code:

<a href="index.php" target="content">Home</a>
<a href="profile.php" target="content">Profile</a>

<iframe src="index.php" name="content" height="500px" width="100%" id="Main_Content" onload="autoResize('Main_Content');"></iframe>

those codes above are working, but I have one problem. consider this scenario:

index.php page height is 800px

and

profile.php page height is 1200px

when i click on the link to index.php page, the iframe resizes to 800px, and then I click the link to profile.php page and the iframe resizes to 1200px BUT this is my problem, when I click again the link to index.php which is the height is smaller than the profile.php page, the iframe is not resizing and not adapting the 800px height and it results in excess space below the content of the index.php which is not looking good, I do not have a problem on growing an iframe height but having some trouble on shrinking it,anyone can give me a hand? any help is appreciated. thanks!

回答1:

Why not just do:

height: auto;
max-height: 1200px;

On the iframe itself within style="" or thru a css doc.

If height is set to auto, then it won't need to use the 1200px for the index.php. But when displaying the profile.php it's allowed to use a maximum of 1200px.



回答2:

I reproduced the problem.

The problem seems to be the use of scrollHeight and scrollWidth which by intention return the current or needed space of the scrollbar, which is not equal to the size of the document itself.

The problem goes away for me when I change

 newheight = document.getElementById(id).contentWindow.document.body.scrollHeight;
 newwidth = document.getElementById(id).contentWindow.document.body.scrollWidth;

into

 newheight = document.getElementById(id).contentWindow.document.body.style.height;
 newwidth = document.getElementById(id).contentWindow.document.body.style.width;

is that doable for you, or is this not under your control?