先看看父頁面的代碼
<div id="sidebar"><ul id="sidenav"><li><a href="1.html" target="myframe">1</a></li><li><a href="2.html" target="myframe">2</a></li></ul></div><div id="main"><iframe src="iframe.html" id="myframe" style="border:none;width:100%;"></iframe></div>
方法一:在父頁面中調節iframe的高度
<script>document.getElementById("myframe").onload=null;function myframeLoadHandler(){var myframe=document.getElementById("myframe");myframe.height=myframe.contentWindow.document.body.scrollHeight+10;}</script>
方法二:在iframe中調節其自身的高度
<script type="text/javascript">function myframeLoadHandler() {if(top.location != self.location){var myframe = parent.document.getElementById('myframe');myframe.height = document.body.scrollHeight+10;}}if(window.addEventListener){window.addEventListener("load",myframeLoadHandler);}else if(window.attachEvent){window.attachEvent("onload",myframeLoadHandler);}else{window.onload=myframeLoadHandler;}</script>
註:以上代碼相容目前的所有瀏覽器;Chrome預設不允許指令碼跨域訪問,如碰到這種情況,以上代碼會無效並報錯