iframe高度自适应

为了让iframe的高度对内容自适应,给iframe标签设置一个onload事件,具体代码如下:

       

js代码:

    //iframe高度自适应(被撑大后,根据内容缩小)

    function reinitIframe(){

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

        try{

            var bHeight = iframe.contentWindow.document.body.scrollHeight;//取iframe中body的高度

            //var dHeight = iframe.contentWindow.document.documentElement.scrollHeight;//取文档高度,包括滚动条内容

var dHeight = 500;-- 当iframe被撑大之后,使用document.documentElement.scrollHeight获取到的文档高度,就大于body(内容)的高度,然后使用 Math.max(bHeight, dHeight)来设置当前iframe的高度时,使用的都是较大值那个,所以,将dHeight设置为固定值即可。

            var height = Math.max(bHeight, dHeight);//取body和文档中较大值为iframe高度

            iframe.height = height;

            console.log("bHeight",bHeight);

            console.log("dHeight",dHeight);

            console.log(height);

        }catch (ex){}

    }

    //定时器,每隔200毫秒,更新一次iframe的高度

    window.setInterval("reinitIframe()", 200);


ps : 若iframe高度自适应后,页面底部存在空白区域,只要将main-content的min-height值改小一点即可。

例如:

你可能感兴趣的:(iframe高度自适应)