auto re-sizing iframe that dynamically changing height (smaller or bigger)

核能气质少年 提交于 2019-12-19 11:44:38

问题


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?



来源:https://stackoverflow.com/questions/19337601/auto-re-sizing-iframe-that-dynamically-changing-height-smaller-or-bigger

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!