您的位置:首页 > 其它

iframe跨域高度自适应

2014-03-20 18:09 218 查看
前言:A域名下main.html页面通过iframe嵌入 B域名下的demo.jsp页面, demo.jsp是动态高度会有变化

A.http://www.9tour.cn/php/x2/www/piaowu.php

main.html中

<iframe id="main_frame" name="main_frame" src='http://xxx.xxx.com/link/iframeLinkIndex_toIframeLinkIndex.action' style="width:1000px;height:1000px;" frameborder='0' onload=""></iframe>
qq

agent.html

<body>
<script>
	function pseth(){
	    var iObj = parent.parent.document.getElementById('main_frame');
	    if(navigator.userAgent.indexOf("Firefox")>0){
		    iObjH = window.location.hash; 
		}else{
 	    	iObjH = parent.parent.frames["main_frame"].frames["agent"].location.hash; 
		}
	    iObj.style.height = iObjH.split("#")[1]+"px"; 
	}
	pseth();
</script>
</body>


B.http://api.114piaowu.com/link/iframeLinkIndex_toIframeLinkIndex.action

: 一个页面 demo.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
XX xx xxx
<iframe id="agent" name="agent" src="" width="0" height="0" style="display:none;" ></iframe>
</body>
<script type="text/javascript">
	function sethash(){
	    var hashH = $(document).height();
// 这个地方的url要注意必须为 main.html同域名
	    var url = "http://www.9tour.cn/php/x2/www/agent.html";
	    if(null!=document.getElementById("agent") && undefined != document.getElementById("agent")){
		    document.getElementById("agent").src=url+"#"+hashH; 
	    }
	}
	window.onload=sethash;
</script>
</html>


注意事项,ifrmae中的js是不支持跨域的,所以通过 一个中间的 页面,动态设置 url+iframe的高度来设置。也就是 例中的 agent.html必须要和main.html 在同域名下面。

思路来源网络,已经测试通过(火狐33.07、ie7、8,chrome低版本会提示 unsafe !,升级就好了)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: