跨域和非跨域 獲取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;" 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>

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM