用javascript動態調整iframe高度

來源:互聯網
上載者:User
當你在頁面上使用了iframe之後,一般來說會不希望iframe顯示難看的捲軸,以使iframe裡面的內容和首頁面的內容渾然一體。這時候你會設定 scrolling="no" 屬性。但是這樣一來如果iframe裡面的內容是變化的,高度會隨之內容的變化而變化的時候,你的iframe就會顯得太長導致底下一大片空白,或者正好相反,由於iframe的高度太小導致一部分內容會被擋住。這裡我提供一個相容IE/NS/Firefox的javascript指令碼實現動態調整iframe的高度。如果需要調整寬度的話,原理是一樣的,本文不加詳述。

首先,在你的首頁面上必須包含以下這段javascript代碼:

<script language="Javascript">
//動態調整iframe高度
var getFFVersion=navigator.userAgent.substring(navigator.userAgent.indexOf("Firefox")).split("/")[1]   
//extra height in px to add to iframe in FireFox 1.0+ browsers   
var FFextraHeight=getFFVersion>=0.1? 16 : 0    
function dyniframesize(iframename) {   
var pTar = null;   
if (document.getElementById){   
   pTar = document.getElementById(iframename);   
} else {   
   eval('pTar = ' + iframename + ';');   
}   
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+FFextraHeight;    
   } else if (pTar.Document && pTar.Document.body.scrollHeight){   
    //ie5+ syntax   
    pTar.height = pTar.Document.body.scrollHeight;   
   }   
}   
}   
</script>

然後對於首頁面用到iframe的地方添加代碼:

<iframe id="myTestFrameID" onload="javascript:{dyniframesize('myTestFrameID');}" marginwidth="0" marginheight="0" frameborder="0" scrolling="no" src="http://www2.zeali.net/myiframesrc.php" width="200" height="100"></iframe>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.