1. 程式人生 > >實現主頁面滾動條隨iframe裡的內容自動調整

實現主頁面滾動條隨iframe裡的內容自動調整

由於網頁中使用到了iframe,如果iframe中的內容超過主頁面的範圍後,在iframe的四周會出現滾動條,這樣和主頁面很不協調,所以在網上找了很久,終於找到一段程式碼可以解決這個問題,程式碼如下: 這段程式碼放在<head></head>之間: <script language="Javascript">
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 FFextraWidth=getFFVersion>=0.1? 16 : 0
var FFextraHeight=getFFVersion>=0.1? 16 : 0 function dyniframesizeWidth(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.offsetWidth){
      //ns6 syntax
      pTar.width = pTar.contentDocument.body.offsetWidth+FFextraWidth;
    }
    else if (pTar.Document && pTar.Document.body.scrollWidth){
      //ie5+ syntax
      pTar.width = pTar.Document.body.scrollWidth;
    }
  }
} function dyniframesizeHeight(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.offsetWidth+FFextraHeight;
    }
    else if (pTar.Document && pTar.Document.body.scrollHeight){
      //ie5+ syntax
      pTar.height = pTar.Document.body.scrollHeight;
    }
  }
}
</script> 下邊是在iframe中輸入的程式碼: <iframe id="displayresult" hspace="0" vspace="0" marginwidth=0 marginheight=0 frameborder=0 width=100% height=100% src="test.htm" scrolling=no name="displayresult"></iframe> 程式碼的關鍵是:設定id                            呼叫js中的函式(dyniframesizeHeight(id)是設定高的滾動條自動調整,dyniframesizeWidth(id)是設定寬的滾動條的自動調整。)                             將scrolling=no                            其他就看實際應用做相應的修改了;