跨域和非跨域 获取iframe页面高度的方法

跨域方法:

第一步,在主页面里插入代码:
//假设主域名是www.aaa.com  需要插入的跨域域名为www.bbb.com

<iframe src="http://www.bbb.com/index.html" width="100%" height="100%" id="iframepage" name="iframepage" onLoad="iFrameHeight()" frameborder="no" border="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>

<script type="text/javascript">
function iFrameHeight() {
var iObj = parent.parent.document.getElementById('iframepage');
iObjH = parent.parent.frames["iframepage"].frames["MiddleIframe"].location.hash;
iObj.style.height = iObjH.split("#")[1] + "px";
}	
</script>


第二步,在跨域页面里(http://www.bbb.com/index.html)插入代码:
//需要在www.aaa.com下新建一个分目录/kuayu下的autoheight.html空文件,否则如果在根目录下建立html文件不确定会不会成功!

<iframe id="MiddleIframe" name="MiddleIframe" src="http://www.aaa.com/kuayu/autoheight.html" width="0" height="0" style="display: none;" οnlοad="on_Height()"></iframe>
<script type="text/javascript">
function on_Height(){
  hashH = document.documentElement.scrollHeight; 
  urlC = "/kuayu/autoheight.htm";
  document.getElementById("MiddleIframe").src=urlC+"#"+hashH; 
}
</script>

 

 

同域名下方法:

只需一步即可:

<iframe src="/abc/default.htm" id="iframepage" width="100%" height="100%" οnlοad="iFrameHeight()"></iframe>
<script type="text/javascript">
function iFrameHeight() { 
  var ifm= document.getElementById("iframepage"); 
  var subWeb = document.frames ? document.frames["iframepage"].document : ifm.contentDocument; 
  if(ifm != null && subWeb != null) { 
    ifm.height = subWeb.body.scrollHeight; 
  } 
}
</script>

  

 

转载于:https://www.cnblogs.com/yanliangnh/p/5889097.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值