跨域iframe自适应

 背景

www.a.com 域下面index.html嵌入www.b.com 域下的content.html页面,此页面会动态变化。要求:

  1. content.html内容为空时,隐藏iframe。
  2. content.html内容变化时,嵌入iframe的高度自适应。

思路

现有主界面index.html在域a下,被嵌套页面content.html在域b下,被嵌套页面content.html又嵌套一个在域a下的代理页面agent.html。当用户打开浏览器访问index.html的时候载入content.html,触发content.html的onload事件获取其自身高度,然后content.html载入agent.html并将高度值作为参数赋值给agent.html的location对象。这样agent.html就可以通过location.hash获得content.html的高度,然后将获取到的content.html的高度传给index.html,然后修改content.html的高度。 

实现

在a域 index.html页面嵌入iframe

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>主页</title>
</head>
<body>
    <div style="border-top: 1px #ccc solid; margin: 10px 0px;" id="J_ContentWrap">
        <iframe src="http://www.b.com/content.html" id="J_Content"
           width="100%" scrolling="no" frameborder="0"></iframe>
    </div>
</body>
</html>

在b域 content.html页面嵌入iframe,src设置为a域的代理页面agent.html,当content.html页面内容动态变化时改变此iframe的src。实现将高度传递给a域。

function sethash(height){
    var hashH;

    if(height != null || height != undefined){
        hashH = height;
    }
    else{
        hashH = $(document.body).outerHeight(true);
    }

    if(document.getElementById("J_Agent")){
        $("#J_Agent").attr('src','http://www.a.com/agent.html?t=' + new Date().getTime() + '#height=' + hashH);
    }
    else{
        $("body").append('<iframe id="J_Agent" style="display:none;" frameborder="0" scrolling="no" ' +
            'marginheight="0" marginwidth="0" ' +
            'src="http://www.a.com/agent.html?t=' + new Date().getTime() + '#height=' + hashH + '" ></iframe>');
    }
}
window.onload=sethash;

改变src值时添加

?t=' + new Date().getTime() 

是为了防止浏览器缓存不能及时的改变iframe大小,页面高度是有参数height=hashH传递的。

在agent.html页面获取height参数,动态设置index.html中iframe的高度,也可在height==0是隐藏iframe或者外层div.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>代理页面</title>
</head>
<script>
    function pseth(){
        var iObj = parent.parent.document.getElementById('J_Content');
        var hash = window.location.hash.slice(1);
        if (hash && /height=/.test(hash)) {
            //iframe中没有内容是参数为0,则隐藏iframe或者外层div
            var height = hash.replace("height=", "");
            if(height == 0){
                parent.parent.document.getElementById("J_ContentWrap").style.display = "none";
            }
            else{
                iObj.height = height;
            }
        }
    }
    pseth();
</script>
</body>
</html>

问题

获取content.html页面的高度,在获取高度时不管是用document.documentElement.scrollHeight 还是document.body.scrollHeight 均存在浏览器兼容性问题。这是强大的jquery帮助了我们,$(document.body).outerHeight(true)

原文地址:https://www.cnblogs.com/pengjv/p/3412876.html