iframe 内容高度在镶边中为空

iframe content height null in chrome

本文关键字:高度 iframe      更新时间:2023-09-26

>我正在使用jQuery根据iframe的内容动态更改其大小,因此它不显示滚动条。该脚本非常简单,在IE9中工作正常,但在chrome中没有任何反应,我添加了一个小的"警报"仅用于debbuging,我发现var"cont_height"没有在chrome中定义。

所有文件都在我的电脑中,包括 iframe 中加载的页面,因此应该没有跨域问题。

chrome 中的调试工具给了我这个错误:"阻止了原点为"null"的帧访问原点为"null"的帧。协议、域和端口必须匹配"。

这是代码

<script type="text/javascript" src="../js/jquery-1.10.2.min.js"> </script>
        <script type="text/javascript">
            $(document).ready(function () {
                $('#mainframe').load(function () {
                    var cont_height = $(this).contents().height();
                    alert(cont_height);
                    $(this).height(cont_height);
                });
            });
        </script>

尝试使用"$(window).load"而不是文档就绪,但我认为这不是时间问题,由于权限或其他原因,我无法访问数据。我真的很感激你能给我的任何提示。解决方案也在javascript中。

这是我发现的根据内容调整 iframe 大小的最佳方法。

<script>
    function resizeMe(id) {
        var theFrame = document.getElementById(id);


        var theBody = (theFrame.contentWindow.document.body || theFrame.contentDocument.body)
        var newHeight = Math.max(theBody.scrollHeight, theBody.offsetHeight, theBody.clientHeight);
        theFrame.height = (newHeight + "px");
    }
</script>

<iframe id="helloworld" ... onload="resizeMe('helloworld')"></iframe>

您可以让 iframe 文档使用 parent.resizeMe('helloworld') 调用父文档。

<body onload="parent.resizeMe('helloworld')">
...
</body>

或者因为你有jquery...

<body>
    ...
    ...
    <script>
        $(document).ready(function(){
            parent.resizeMe('helloworld');
        });
    </script>
</body>