chrome中的iframe内容高度为null

时间:2013-09-25 16:05:28

标签: javascript jquery html iframe

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

所有文件都在我的计算机中,包括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。

1 个答案:

答案 0 :(得分: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>

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

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

或者因为你有jquery ......

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

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

</body>