IFrame高度设置

来源:互联网 发布:数据处理软件pen 编辑:程序博客网 时间:2024/05/01 01:16

由于最近想实现网页局部刷新,使用的IFrame,只要给IFrame赋给新的src值,便可以加载不同的页面了。但让人烦恼的问题也随之而来了,那便是如何让IFrame自身的高度随子页面而变化。上网搜了好多方法,发现都不适用。

很多人的方法都是这样的。在IFrame中设置 onload="autoHeight();“

function autoHeight(){

        var iframe =document.getElementById("container");

        if(iframe.Document){//ie自有属性

            iframe.style.height =iframe.Document.documentElement.scrollHeight;

        }elseif(iframe.contentDocument){//ie,firefox,chrome,opera,safari

            iframe.height =iframe.contentDocument.body.offsetHeight ;

        }

    }


这种方法在FireFox和Chrome中显示很好,但是在IE中完全不好使,后来才发现,在IE中不能用iframe.Document,得用iframe.contentWindow。

修改之后的代码为:

function autoHeight(){

        var iframe = document.getElementById("container");

        if(iframe.Document){//ie自有属性

        iframe.style.height =  iframe.contentWindow.document.body.scrollHeight+20;

        }else if(iframe.contentDocument){//ie,firefox,chrome,opera,safari

            iframe.height=10;

            iframe.height = iframe.contentDocument.body.offsetHeight;

        }

    }

这样在IE、FireFox和Chrome中就都好使了。


原创粉丝点击