具有可扩展内容的 iframe 自动调整大小

iframe autosize with expandable content

本文关键字:调整 iframe 可扩展      更新时间:2023-09-26

我正在构建一个页面,需要使用iframe,以便我们可以对内容进行包装,也可以在没有内容的情况下显示它。我已经能够想出一些自动检测 iframe 高度的 JS,但其中的内容会扩展并且 iframe 无法识别这一点。我假设我需要在框架内容中提出某种 onclick,这将触发 iframe 再次调整大小,但到目前为止一直卡住了。

下面是我在 head 部分中用于自动调整 iframe 大小的函数的 JS:

<script type="text/JavaScript">

    function autoResize(id){
        //alert('check');
        var newheight;
        var newwidth;
        if(document.getElementById){
            newheight=document.getElementById(id).contentWindow.document .body.scrollHeight;
            newwidth=document.getElementById(id).contentWindow.document .body.scrollWidth;
        }
        //alert(newheight);
        //alert(newwidth);
        document.getElementById(id).height= (newheight) + "px";
        document.getElementById(id).width= (newwidth) + "px";
    }

    </script>

然后这是带有加载和 ID 的 iframe:

<iframe id="showcase" src="index.html" onload="javascript: autoResize('showcase');" frameborder="0" width="800px" height="4000" scrolling="no"></iframe>

感谢您的任何帮助,我希望我在这个问题上足够具体。

我不确定,但我假设您可以使用 DOM 突变事件来设置帧更改中body对象的offsetWidth/offsetHeight属性的事件处理程序并调用autoResize

同样,我不确定这是否可行。