解决iframe跨域高度自适应问题(zhuanzai)
前期因项目需要解决iframe跨域高度自适应问题,但在网上找了许久也没找到能用的,几乎都是转载的,也没经过测试,当时就不了了知了。最近该项目又要实现这种功能,没办法,硬着头皮也要上呀。通过查阅资料及加上自己的理解,总算实现了这个功能,在这暂存以备后查。
交待下项目背景。两个独立的项目A与B且为独立的域名就叫做 www.abc.com与www.efg.com吧。在A项目中要调用B项目的一个页面并且被嵌入的页面中有链接的,点击链接会跳转到新页面,所以页面高度就会变化,需要的效果就是iframe的高度根据页面的内容自动调整。
页面准备:共需要三个页面,A项目两个页面,一个是要嵌入B项目页面的框架页面,叫iframe页面吧,另个是中间代理页面,叫agent页面吧;B项目需要一个页面,那就是要被iframe页面嵌套的页面,就叫content页面吧。
实现方法:在content页面中加上一段JavaScript代码,主要功能就是获取当前页面的高度,然后在该页面中插入个隐藏的iframe去访问agent页面,并在链接地址后加上content页面高度,看代码吧:
$(function(){ var h = $(document.body).outerHeight(true); $("body").append('<iframe style="display:none;" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://www.abc.com/agent.html?t='+ new Date().getTime()+'#height=' + h + '" ></iframe>'); }); var hash = window.location.hash.slice(1); if (hash && /height=/.test(hash)) { window.top.location.hash = "#" + hash; } var iframe = document.getElementById("iframe");//iframe的ID var iframeHeight = function() { var hash = window.location.hash.slice(1); if (hash && /height=/.test(hash)) { iframe.height = hash.replace("height=", ""); } }; setInterval(iframeHeight, 500);