自动调整动态改变高度(更小或更大)的iframe

时间:2013-10-12 18:16:50

标签: javascript jquery html iframe

我知道有很多关于重新调整大小iframe的帖子,但我找到的只是这段代码:

<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>

这是样本标记代码:

<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>

上面的代码正在运行,但我有一个问题。考虑这种情况:

index.php page height is 800px

profile.php page height is 1200px

当我点击指向index.php页面的链接时,iframe会调整为800px,然后点击指向profile.php页面的链接,iframe会调整为{ {1}}但这是我的问题,当我再次点击1200px的链接时,index.php页面的高度小于profile.phpiframe没有调整大小,也没有调整800px身高index.php导致{{1}}内容空间不足,看起来不太好,我在增加iframe高度方面没有问题,但在缩小它时遇到一些麻烦,任何人都可以给我一只手?任何帮助表示赞赏。谢谢!

2 个答案:

答案 0 :(得分:0)

为什么不这样做:

height: auto;
max-height: 1200px;

在style =“”内的iframe本身或通过css doc。

如果height设置为auto,那么它将不需要使用1200px作为index.php。但是当显示profile.php时,允许使用最大1200px。

答案 1 :(得分:0)

我重现了这个问题。

问题似乎是使用scrollHeight和scrollWidth,它意图返回滚动条的当前或所需空间,这不等于文档本身的大小。

当我改变

时,问题就消失了
 newheight = document.getElementById(id).contentWindow.document.body.scrollHeight;
 newwidth = document.getElementById(id).contentWindow.document.body.scrollWidth;

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

对你来说是可行的,还是这不在你的掌控之中?