iframe自适应高度 iframe

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhai_15733218875/article/details/79005623

本以为在前端道路上不会用到iframe,毕竟html5已经废弃了。但是项目中还是遇到了,于是各种百度开始啦
下面是我百度到的代码:

<iframe id="iframe"  scrolling="no" frameborder="0" style="width:540px;text-align: center;"  src="aaa.html?shop_id=26"></iframe>


var ifm = document.getElementById("iframe");
    ifm.onload = function() {
        var subWeb = document.frames ? document.frames["iframe"].document : ifm.contentDocument;
        if (ifm != null && subWeb != null) {
        ifm.height = subWeb.body.scrollHeight + 44;
        alert(ifm.height)
        }
    }

然后在我写的时候这还没有完,因为iframe的高度和之前一样,并没有自适应,后来我找到了src中引用的页面 ,显式的获取页面文档高度 给body元素
document.body.offsetHeight
这样就可以啦..

但是 由于rc中引用的页面存在异步, 上面的方法需要放到ajax 成功的回调之后

由于本人的项目 那个页面有多个ajax封装的方法, 所以索性 更改代码:

var ifm = document.getElementById("iframe");
    ifm.onload = function() {
        var subWeb = document.frames ? document.frames["iframe"].document : ifm.contentDocument;
        setTimeout(function() {
            if (ifm != null && subWeb != null) {
            ifm.height = subWeb.body.scrollHeight + 44;
            alert(ifm.height)
            }
        }, 4000)
    }

iframe嵌进去的页面是不可点击的,设置一下样式就可以

<style>  
    iframe{  
        pointer-events: none;  
    }  
</style>  

嗯 就这样,之后再优化

今天没事了 改了一下 把setTimeout改成了setInterval,代码如下:

var ifm = document.getElementById("iframe");
    ifm.onload = function() {
        var subWeb = document.frames ? document.frames["iframe"].document : ifm.contentDocument;
        var heightArray = [];
        var interval = setInterval(function() {

            if (ifm != null && subWeb != null) {
                ifm.height = subWeb.body.scrollHeight + 44;
            }

            heightArray.push(ifm.height);

            if(heightArray.length > 1) {
                if(heightArray[heightArray.length-2] === heightArray[heightArray.length-1]) {
                    clearInterval(interval)
                }
            }

        }, 1200)

    }

猜你喜欢

转载自blog.csdn.net/zhai_15733218875/article/details/79005623