美文网首页
iframe高度自适应

iframe高度自适应

作者: 相约最好的自己 | 来源:发表于2018-06-23 14:41 被阅读0次

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

    <div class="middle-section">

            <iframe id = "test" class="sticky-header" src="" name="index" frameborder="0"         width="100%" style="background-color: #fff" onload="this.height=100;"></iframe >

    </div>

    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高度自适应

          本文链接:https://www.haomeiwen.com/subject/fknryftx.html