让前端飞Web前端之路

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

2019-11-05  本文已影响0人  2o壹9

跨域方法:

第一步,在主页面里插入代码:

//假设主域名是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;" onload="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%" onload="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>

上一篇 下一篇

猜你喜欢

热点阅读