问题:
A域名下的页面a.htm中通过iframe嵌入B域名下的页面b.html,由于b.html的大小等是不可预知而且会变化的,所以需要a.htm中的iframe自适应大小.
问题本质 :
js的跨域问题,因为要控制a.htm中iframe的大小就必须首先读取得到b.html的大小,A、B不属于同一个域,js的访问受限,读取不到b.html的大小.
解决方案:
首先前提是A,B是合作关系,b.html中能引入A提供的js
首先a.html中通过iframe引入了b.html
- <iframe id="aIframe" height="0" width="0"
- src="http://www.b.com/html/b.html" frameborder="no" border="0px" marginwidth="0"
- marginheight="0" scrolling="no" allowtransparency="yes" ></iframe>
<iframe id="aIframe" height="0" width="0" src="http://www.b.com/html/b.html" frameborder="no" border="0px" marginwidth="0" marginheight="0" scrolling="no" allowtransparency="yes" ></iframe>
B在b.html中引入了A提供的js文件
- <script language="javascript" type="text/javascript"
- src="http://www.a.com/js/a.js"></script>
该js首先读取b.html的宽和高,然后创建一个iframe,src为和A同一个域的中间代理页面a_proxy.html,吧读取到的宽和高设置到src的hash里面
- <iframe id="iframeProxy" height="0" width="0"
- src="http://www.a.com/html/a_proxy.html#width|height" style="display:none" >
- </iframe>
- var pParentFrame = parent.parent.document.getElementById("aIframe");
- var locationUrlHash =
- parent.parent.frames["aIframe"].frames["iframeProxy"].location.hash;
- pParentFrame.style.width = locationUrlHash.split("#")[1].split("|")[0]+"px";
- pParentFrame.style.height = locationUrlHash.split("#")[1].split("|")[1]+"px";
其他一些类似js跨域操作问题也可以按这个思路去解决