作家
登录

js跨域问题之跨域iframe自适应大小实现代码

作者: 来源:www.28hudong.com 2013-03-30 01:26:33 阅读 我要评论

复制代码 代码如下: <body onload="javascript: setHeight();"> <script> function setHeight(){ var dHeight = document.documentElement.scrollHeight; var t = document.createElement("div"); t.innerHTML = '<iframe id="kxiframeagent" src="http://rest.kaixin001.com/api/agent.html#'+dHeight+'"scrolling="yes" height="0px" width="0px"></iframe>'; document.documentElement.appendChild(t.firstChild); } </script> 我想着跨域如何解决啊!后来去网上搜索了一下子 恍然大悟 具体如下 我是复制过来了 大家重点理解一下子它的实现思路 : 问题: 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文件 Html代码 复制代码 代码如下: <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里面 Html代码 复制代码 代码如下: <iframe id="iframeProxy" height="0" width="0" src="http://www.a.com/html/a_proxy.html#width|height" style="display:none" ></iframe> a_proxy.html是A域下提供好的中间代理页面,它负责读取location.hash里面的width和height的值,然后设置与 它同域下的a.html中的iframe的宽和高. Js代码 复制代码 代码如下: 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"; 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"; 这样的话a.html中的iframe就自适应为b.html的宽和高了. 其他一些类似js跨域操作问题也可以按这个思路去解决

  推荐阅读

  Date对象格式化函数代码

复制代码 代码如下: /* * Date Format 1.2.3 * (c) 2007-2009 Steven Levithan * MIT license * * Includes enhancements by Scott Trenda * and Kris Kowal * * Accepts a date, a mask, or a date and a mask. *>>>详细阅读


本文标题:js跨域问题之跨域iframe自适应大小实现代码

地址:http://www.17bianji.com/kaifa2/JS/26010.html

关键词: 探索发现

乐购科技部分新闻及文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与乐购科技进行文章共享合作。

网友点评
自媒体专栏

评论

热度

精彩导读
栏目ID=71的表不存在(操作类型=0)