1

我正在使用 jQuery 根据其内容动态更改 iframe 的大小,因此它不会显示滚动条。该脚本非常简单,在 IE9 中运行良好,但在 chrome 中没有任何反应,我添加了一个仅用于调试的小“警报”,我发现 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 中使用。

4

1 回答 1

1

这是我发现根据内容调整 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>

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

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

或者因为你有 jquery...

<body>
    ...
    ...
    <script>

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

</body>
于 2013-09-25T16:28:10.220 回答