Heim  >  Artikel  >  Web-Frontend  >  跨域下iframe自适应高度_html/css_WEB-ITnose

跨域下iframe自适应高度_html/css_WEB-ITnose

WBOY
WBOYOriginal
2016-06-24 11:28:501333Durchsuche

最近在做一个需求,需求大致背景:页面中iframe嵌入另一家公司的列表页

博主的第一反应就是“very easy!”,so,挽起双袖开始敲代码

结果出现问题了,iframe跨域,无法获得内嵌页面的高度,因此出现的上下滚动条,so难看!

于是上网找大神,皇天不负有心人啊,终于找到了,激动之情无以言表....

故事背景交代完毕

/******************************华丽的分割线,哈哈****************************/

大神的例子大致是这样的:

假设www.a.com下的一个页面a.html要包含www.b.com下的一个页面c.html。

我们使用www.a.com下的另一个页面agent.html来做代理,通过它获取iframe页面的高度,并设定iframe元素的高度

a.html中包含iframe:

1 <iframe src="http://www.b.com/c.html" id="Iframe" frameborder="0" scrolling="no" style="border:0px;"></iframe>

在c.html中加入如下代码:

1 <iframe id="c_iframe"  height="0" width="0"  src="http://www.a.com/agent.html" style="display:none" ></iframe>2 <script type="text/javascript">3 (function autoHeight(){4 var b_width = Math.max(document.body.scrollWidth,document.body.clientWidth);5 var b_height = Math.max(document.body.scrollHeight,document.body.clientHeight);6 var c_iframe = document.getElementById("c_iframe");7 c_iframe.src = c_iframe.src + "#" + b_width + "|" + b_height;  // 这里通过hash传递b.htm的宽高8 })();9 </script>

最后,agent.html中放入一段js:

 1 <script type="text/javascript"> 2 var b_iframe = window.parent.parent.document.getElementById("Iframe"); 3 var hash_url = window.location.hash; 4 if(hash_url.indexOf("#")>=0){ 5 var hash_width = hash_url.split("#")[1].split("|")[0]+"px"; 6 var hash_height = hash_url.split("#")[1].split("|")[1]+"px"; 7 b_iframe.style.width = hash_width; 8 b_iframe.style.height = hash_height; 9 }10 </script>

agent.html从URL中获得宽度值和高度值,并设置iframe的高度和宽度(因为agent.html在www.a.com下,所以操作a.html时不受JavaScript的同源限制)

 

文章引用:前端开发博客

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn