跨域问题是由于javascript语言安全限制中的同源策略造成的。出于安全方面的考虑,不允许跨域调用其他页面的对象。

例如:a域名下,www.a.com/index.html需要引用b域名下,www.b.com/quote.html页面,但引用的这个b域名下页面里面内容高度不确定。此时就需要双方技术共同解决,利用iframe和location.hash方法。

在a域名下,添加一个判断页agent.html,添加以下代码:

<script>
function  pseth() {
     var iObj = parent.parent.document.getElementById('iframeB'); //A和main同域,所以可以访问节点
     iObjH = parent.parent.frames["iframeB"].frames["iframeA"].location.hash; //访问自己的location对象获取hash值
     iObj.style.height = iObjH.split("#")[1]+"px"; //操作dom
}
pseth();
</script>

在b域名,quote页面中添加如下代码:

<iframe id="iframeA" name="iframeA" src="" width="0" height="0" style="display:none;" ></iframe>
<script type="text/javascript">
     function sethash(){
          hashH = document.documentElement.scrollHeight; //获取自身高度
          urlC = "http://www.a.com/agent.html"; //设置iframeA的src
          document.getElementById("iframeA").src=urlC+"#"+hashH; //将高度作为参数传递
    }
     window.onload=sethash;
</script>

在a域名,index页面中添加如下代码:

<iframe id="iframeB" name="iframeB" src="http://www.b.com/quote.html" width="100%" height="auto" scrolling="no" frameborder="0"></iframe>

关于跨域的具体介绍,可以参考:JavaScript跨域总结与解决办法

感谢您的阅读,本文由 蓝色梦想 版权所有。如若转载,请注明出处:蓝色梦想 - iframe跨域 自适应高度