iframe自适应高度的方法

不带边框的iframe因为能和网页无缝的结合从而不刷新新页面的情况下实现更新页面部分的数据成为可能,可是iframe却不像层那样可以收缩自如,iframe高度需要动态的调整需要JS来配合使用,只能通过JS动态的来赋给他高度。

function SetWinHeight(obj)
{
  var win=obj;
  if (document.getElementById)
  {
    if (win && !window.opera)
    {
      if (win.contentDocument && win.contentDocument.body.offsetHeight)
        win.height = win.contentDocument.body.offsetHeight;
      else if(win.Document && win.Document.body.scrollHeight)
        win.height = win.Document.body.scrollHeight;
    }
  }

}

<iframe width="778" align="center" height="200" id="win" name="win" onload="Javascript:SetWinHeight(this)" frameborder="0" scrolling="no" src="1.htm"></iframe>

或者:

<script language="javascript" type="text/javascript">
  function dyniframesize(down) {
    var pTar = null;
    if (document.getElementById){
    pTar = document.getElementById(down);
  }
  else{
    eval('pTar = ' + down + ';');
  }
  if (pTar && !window.opera){
    //begin resizing iframe
  pTar.style.display="block"
  if (pTar.contentDocument && pTar.contentDocument.body.offsetHeight){
  //ns6 syntax
    pTar.height = pTar.contentDocument.body.offsetHeight +20;
    pTar.width = pTar.contentDocument.body.scrollWidth+20;
  }
  else if (pTar.Document && pTar.Document.body.scrollHeight){
    //ie5+ syntax
    pTar.height = pTar.Document.body.scrollHeight;
    pTar.width = pTar.Document.body.scrollWidth;
  }
  }
}
</script>
<iframe src ="/default2.aspx" frameborder="0" marginheight="0" marginwidth="0" frameborder="0" scrolling="auto" id="ifm" name="ifm" onload="javascript:dyniframesize('ifm');" width="100%">
</iframe>

原文地址:https://www.cnblogs.com/jsingleegg/p/3953628.html