有时在项目中会遇到通过在页面中采用iframe的方式include其它页面,这时就会考虑不要因出现滚动条而影响页面效果,但include页面的内容高度是未知的,所以大家都会利用javascript来解决这个高度自适应的问题。

在网上曾看见过解决此问题的代码,不过拷贝到本地进入调试时有些不正常,在IE下无法正确获得嵌套页面的高度,通过各种尝试,最终代码如下

<script type="text/javascript"> 
 function SetCwinHeight(iframeObj){ 
  if (document.getElementById){ 
   if (iframeObj && !window.opera){ 
    if (iframeObj.contentDocument && iframeObj.contentDocument.body.offsetHeight){ 
     iframeObj.height = iframeObj.contentDocument.body.offsetHeight; 
    }else if(document.frames[iframeObj.name].document && document.frames[iframeObj.name].document.body.scrollHeight){ 
     iframeObj.height = document.frames[iframeObj.name].document.body.scrollHeight; 
    } 
   } 
  } 
 } 
 </script> 
 <iframe width="100%" name="frameContent" onload="SetCwinHeight(this)" frameborder="0" src="*"></iframe>

扩展:

在一个页面含有某个iframe,其)取到的是iframe组件对象,通过该对象可以获取到iframe所包含的页面的子页面的各个对 象,例如子页面的window对象,但是不能获得iframe标签得各个属性,例如上面说到的src等等。

相关文章: